我应该在哪里保存申请数据?

时间:2017-05-10 19:47:16

标签: c#

我已经尝试了很多方法来获取一个目录,我可以保存一个需要保留在那里的应用程序的.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);

2 个答案:

答案 0 :(得分:3)

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

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

...然后代表一个文件...

client.DownloadFile(downloadUrl, savePath);

尝试将文件下载到%UserProfile%\Fox\example.txt将失败,并在example.txt已作为目录存在时指定例外。以下代码段演示了您遇到的问题并非文件下载所特有的:

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

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

答案 1 :(得分:0)

将清单文件添加到项目中需要管理员权限才能解决此问题。