简体   繁体   中英

System.IO.WriteAllBytes - Access to path denied error

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.

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.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM