I have a method that is opening a .txt file for reading only. I have it working well but now I am trying to ensure that I don't access the file if someone else has it open. I have tried other solutions but I'm still having issues.
public string Load()
{
string source = MessagesAndNotifications.SourceDrawingNotSet;
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = false;
openFileDialog.Filter = "afile (*.txt)|*.txt";
Nullable<bool> result = openFileDialog.ShowDialog();
FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
if (fileInfo.IsReadOnly == false)
{
if (result == true)
{
try
{
using (var fileStream = File.Open(openFileDialog.FileName, FileMode.Open,
FileAccess.Read, FileShare.None))
{
using (var streamReader = new StreamReader(fileStream.Name))
{
//rest of the code goes on...
}
The problem is my check on IsReadOnly is returning false even though I have opened the file myself. Then when my program gets to the try statement it catches the file being open and the program throws an exception and crashes.
I had originally tried having the File.OpenRead()
method instead of File.Open()
with parameters and got the same result.