System.IO.WriteAllBytes - Access to path denied error

33,442

Solution 1

Make sure that you specify the entire path when using File.WriteAllBytes() including file name.

File.WriteAllBytes() cannot write to a general directory, it has to write to a specific file.

Hope this helps.

Solution 2

In windows7 there are security issues on c:. If you modified the path to D: then no access denied issue will be there.

Try following sample code with Path.GetTempPath(), it will execute successfully.

    static void Main(string[] args)
    {
        string path = Path.GetTempPath();
        byte[] binaryData;
        string text = "romil123456";
        using (MemoryStream memStream = new MemoryStream(Encoding.ASCII.GetBytes(text)))
            {
                binaryData = memStream.ToArray();
            }
            System.IO.File.WriteAllBytes(@path + "\\words123.txt"    , binaryData);
        }
    }

Environment.SpecialFolder.ApplicationData provides the folder name, not provides the full path to that folder. so when you use this in path defined to write file, this folder is searched under in local application path.

Solution 3

Are you sure the file isn't still locked? If you are planning to read + write bytes from a file, you might want to consider using a Stream class (for example the FileStream), the advantage is that you will lock the file and that no other application can access the file in the meantime.

Code example from this topic:

FileStream fileStream = new FileStream(
  @"c:\words.txt", FileMode.OpenOrCreate, 
  FileAccess.ReadWrite, FileShare.None);
Share:
33,442

Related videos on Youtube

user1097734
Author by

user1097734

Updated on July 09, 2022

Comments

  • user1097734
    user1097734 over 1 year

    Currently developing a C# WinForms application in Visual Studio 2010 .NET 4 on Windows 7.

    Firstly I am reading a stream of bytes from a file using the File.ReadAllBytes() method. Then when attempting to write the file back, I am getting a access to path denied error when using the WriteAllBytes method.

    I have tried passing in literal paths, Environment.SpecialFolder.ApplicationData, Path.GetTempPath(), but all are providing me with the same error.

    I have checked permissions on these folders and also attempted to start the program in administrator mode with no luck.

    • Steve Danner
      Steve Danner
      Can you post your code ?
  • user1703401
    user1703401 over 11 years
    A locked file produces an entirely different exception.
  • Styxxy
    Styxxy over 11 years
    You are right, it gives an System.IO.IOException if the file is locked.
  • ShadowKras
    ShadowKras almost 6 years
    This error is not exclusive to c:, iv experienced it on all my drives on windows 10.

Related