I have an application with two forms.
In the first form (MainMenu) I declare and initialize a FileStream to lock a specific file. In the second form (EdiMenu) I just declare another FileStream.
When the user clicks on a button the FileStream and file lock should be given to the FileStream in form two and the first form will close.
public partial class MainMenu : Form
{
EdiMenu Edi_Menu; // Second form
private string applicationConfigurationFile = "configuration.xml";
private FileStream configurationFile;
private void mainMenu_Load(object sender, EventArgs e)
{
configurationFile = new FileStream(applicationConfigurationFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
configurationFile.Lock(1, configurationFile.Length);
}
private void LoadEdiForm_Click(object sender, EventArgs e)
{
XDocument xdoc = XDocument.Load(applicationConfigurationFile); // Throws an exception
XDocument xdoc = XDocument.Load(configurationFile); // Works
// Code to check the file content
Edi_Menu = new EdiMenu();
Edi_Menu.configurationFilePublic = configurationFile;
Edi_Menu.Show();
this.Close(); // First form terminates here and the second form remains
}
}
// Second Class/Form
public partial class EdiMenu : Form
{
private string applicationConfigurationFile = "configuration.xml";
private FileStream configurationFile;
public FileStream configurationFilePublic
{
get { return configurationFile; }
set { configurationFile = value; }
}
private void FillDatagrid()
{
XDocument xdoc = XDocument.Load(applicationConfigurationFile); // Throws an exception
XDocument xdoc = XDocument.Load(configurationFile); // Throws an exception
}
}
In the second form it throws an exception when I wan't to read the file with XDocument, no matter if I pass the string or the FileStream.
Could someone point me to the right direction, how to lock a file from application start to application end and how to use the locked file from everywhere in the application without having an exception that the file is locked by another process?
This works the first time:
XDocument xdoc = XDocument.Load(configurationFile);
The reason it throws an exception when you try to read it the second time is because you need to reset the stream position.
In your second form, reset the stream position before attempting to load the stream again:
configurationFile.Position = 0;
XDocument xdoc2 = XDocument.Load(configurationFile);