Search code examples
c#streamreaderstreamwriter

System.UnauthorizedAccessException when trying to open a StreamWriter with a previously opened file


I'm trying to write to a hidden file after reading it/using a default value. After trying to reopen a StreamWriter, I get an UnauthorizedAccessException, telling me that access to the file is denied, but without any useful information in it (at least I think there isn't).

I've tried Googling the issue, but no one has seemed to run into the issue.

I've also tried creating a FileStream to force admission to write, as well as tried closing the reader beforehand, but to no avail. I think I'm missing something so obvious, but I can't for the life of me figure it out.

Assembly assembly = Assembly.GetExecutingAssembly();
String filePath = assembly.Location.Substring(0, assembly.Location.LastIndexOf('.')) + " - Last Used Rounding";

RoundingIndex index = RoundingIndex.Nearest_8;  //The nearest 8th is the default.
if (File.Exists(filePath))
{
    using (StreamReader reader = new StreamReader(filePath))
    {
        try
        {
            int value = int.Parse(reader.ReadLine());

            foreach (RoundingIndex dex in Enum.GetValues(typeof(RoundingIndex)))
            {
                if (value == (int) dex)
                {
                    index = dex;

                    break;
                }
            }
        }
        catch
        {
            //Recreate the corrupted file.
            reader.Close();

            File.Delete(filePath);

            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.WriteLine((int) index);
            }

            File.SetAttributes(filePath, FileAttributes.Hidden);
        }
    }
}
else
{
    using (StreamWriter writer = new StreamWriter(filePath))
    {
        writer.WriteLine((int) index);
    }

    File.SetAttributes(filePath, FileAttributes.Hidden);
}


//
//Process information here and get the next "last rounding".
//


using (StreamWriter writer = new StreamWriter(filePath))    //Exception getting thrown here.
{
    writer.WriteLine((int) RoundingIndex.Nearest_16);
}






//In case there is any question:
public enum RoundingIndex
{
    Nearest_2 = 2,
    Nearest_4 = 4,
    Nearest_8 = 8,
    Nearest_16 = 16,
    Nearest_32 = 32,
    Nearest_64 = 64,
    Nearest_128 = 128,
    Nearest_256 = 256
}

Solution

  • You need to change the 'hidden' state before modifying its contents.

    FileInfo myFile = new FileInfo(filePath);
    myFile.Attributes &= ~FileAttributes.Hidden;
    

    afterwards, you can set the state back

    myFile.Attributes |= FileAttributes.Hidden;