0

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.

Kefka
  • 89
  • 7
  • Also `gets to the try statement it catches the file being open and the program throws an exception and crashes` are you `catch`ing this exception? – Trevor Jan 03 '20 at 16:28
  • 1
    No amount of "pre-checking" can prevent the state of the file changing between performing those checks and actually attempting to open the file - so just go ahead, open the file, and be prepared to handle the exception if/when it's thrown. – Damien_The_Unbeliever Jan 03 '20 at 16:29
  • @Çöđěxěŕ thanks I will check that out. I am catching the exception down lower in the code. Damien, I will take that advice thank you. – Kefka Jan 03 '20 at 16:31

2 Answers2

1

The "IsReadonly"-Attribute on the FileSystem has nothing to do with the opening-Mode.

If a file is readonly, you can only read it. But if a file is not readonly, you still can open it for reading, and read it only.

Holger
  • 2,446
  • 1
  • 14
  • 13
  • Thanks I think in this case my original code of using `File.OpenRead()` is the right solution then. – Kefka Jan 03 '20 at 16:33
1

FileInfo.IsReadOnly only checks if the file attribute "read-only" is true, not if the file is in use. At least, to the best of my understanding.

https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo.isreadonly?view=netframework-4.8

The only way I could see that approach working is if the "read-only" flag is added to the file whenever somebody opens it.

I would instead suggest researching "in use" solutions:

Is there a way to check if a file is in use?

dvro
  • 163
  • 7