简体   繁体   中英

C# Filestream denied access

我正在尝试使用 C# 创建文件,然后读回文件以填写富文本块。现在我的问题是创建\/写入文件。

FileStream fs = File.Create(@".\\tmp\" + fileName);

The probably is that the user that is running the application probably doesn't have access to write to that directory. The easiest way to test that would be to run your application as administrator you should have access to write to that directory then.

You might also want to consider writing to the current directory no matter what user who is running your application should at the very least have access to that directory

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)

Probably you don't have access to the relative path. To get your assembly directory:

private static string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}

Then

FileStream fs = File.Create(Path.Combine(AssemblyDirectory, fileName));

You are using a relative path which leads to a location which you don't have access to.

A possible solution could be to:

  1. Create a folder C:/data and make sure you have read and write rights to that folder

  2. change the code to

     string fileName = "file.txt"; FileStream fs = File.Create(@"C:/data/" + fileName); 

This should create a file under C:/data with the filename "file.txt", assuming you have the correct read and write rights.

If you want a relative path to the current user's root directory, use:

string currentUserDirectory = 
       Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

This happened to me . I had had an anti-virus blocking access to any file when the writing or reading process happening from a C# program. I have just deactivated the anti-virus and the code worked like magic !

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