我尝试了很多方法来获取一个目录,我可以在其中保存需要留在那里的应用程序的 .exe,但是我尝试的每个目录都说拒绝访问。

我应该为此写什么路径?肯定必须有一个管理员权限不正确的路径?我确定我以前见过这样做过..

我尝试了什么?

Environment.GetFolderPath(
    Environment.SpecialFolder.CommonApplicationData)


Path.GetTempPath()

和这个
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)

有人可以帮忙吗?这是我的完整代码,也许与下载有关?
string downloadUrl = "http://example.com/example.txt";
string savePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "/Fox/example.txt";

if (!Directory.Exists(savePath))
{
    Directory.CreateDirectory(savePath);
}

using (var client = new WebClient())
{
    client.DownloadFile(downloadUrl, savePath);
    Process.Start(savePath);
}

通常会遇到这些方面的异常
System.Net.WebException occurred
  HResult=0x80131509
  Message=An exception occurred during a WebClient request.
  Source=System
  StackTrace:
   at System.Net.WebClient.DownloadFile(Uri address, String fileName)
   at System.Net.WebClient.DownloadFile(String address, String fileName)
   at App.Program.Main(String[] args) in c:\users\user\documents\visual studio 2017\Projects\App\App\Program.cs:line 26

Inner Exception 1:
UnauthorizedAccessException: Access to the path 'C:\Users\User\App\example.txt' is denied.

异常行:
client.DownloadFile(downloadUrl, savePath);

最佳答案

问题是您首先使用 savePath 来表示目录...

if (!Directory.Exists(savePath))
{
    Directory.CreateDirectory(savePath);
}

...然后代表一个文件...
client.DownloadFile(downloadUrl, savePath);

尝试将文件下载到 %UserProfile%\Fox\example.txt 将失败,当 example.txt 已作为目录存在时,您会指定异常(exception)。以下代码段表明您遇到的问题并非文件下载所独有:
// Build a path to a file/directory with a random name in the user's temp directory
// Does not guarantee that path does not already exist, but assume it doesn't
string path = Path.Combine(
    Path.GetTempPath(), Path.GetRandomFileName()
);
// Create a directory at that path
DirectoryInfo directory = Directory.CreateDirectory(path);

// Create a file at the same path
// Throws UnauthorizedAccessException with message "Access to the path '...' is denied."
using (FileStream stream = File.Create(path))
{
}

考虑将您的代码更改为以下内容以避免此问题:
string downloadUrl = "http://example.com/example.txt";
string saveDirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "/Fox";
string saveFilePath = saveDirectoryPath + "/example.txt";

if (!Directory.Exists(saveDirectoryPath))
{
    Directory.CreateDirectory(saveDirectoryPath);
}

using (var client = new WebClient())
{
    client.DownloadFile(downloadUrl, saveFilePath);
    Process.Start(saveFilePath);
}

请注意,我建议在构建路径时使用 Path.Combine 而不是 string 连接:
string saveDirectoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Fox");
string saveFilePath = Path.Combine(saveDirectoryPath, "example.txt");

它是跨平台的,可以为您处理所有必要的逻辑。

关于c# - 我应该在哪里保存应用程序数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43901510/

10-10 18:12