我遇到了一个正在开发的 Windows 应用程序的情况,其中 DownloadFile 抛出“找不到路径的一部分”异常。
我用来将远程 zip 文件保存到我的硬盘驱动器的方法如下所示:
private void f_begin_download(string remoteURL)
{
string directoryName = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
//MessageBox.Show(directoryName);
filePath = directoryName + "\\tmp\\";
filePath = f_make_directory(filePath);
Uri remoteURI = new Uri(remoteURL);
System.Net.WebClient downloader = new System.Net.WebClient();
downloader.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(f_downloader_DownloadFileCompleted);
try
{
downloader.DownloadFile(remoteURI, filePath);
}
catch (Exception ex)
{
MessageBox.Show(remoteURI.ToString());
MessageBox.Show(filePath);
MessageBox.Show(ex.ToString());
}
}
此方法实际上在我的应用程序目录中创建了/tmp/文件夹。它也成功创建了文件夹:
public static string f_make_directory(string path)
{
try
{
System.IO.DirectoryInfo newFolder = new System.IO.DirectoryInfo(path);
if (!newFolder.Exists)
{
newFolder.Create();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return path;
}
但是当我运行这个过程时,异常看起来是这样的:
System.Net.WebException: An exception occurred during a WebClient request. --> System.IO.DirectoryNotFoundException: Could not find a part of the path' C:\Users\Hudson Atwell\Desktop\The Big Test Folder\tmp\'.
at System.IO.__Error.WinIOError(Int32 errorCode,String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRight, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msyPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access) at System.Net.WebClient.DownloadFile(Uri address, String fileName)
在 WindowsFormsApplication1.window_updater.f_begin_download(String remoteURL) 在 C:\Users\Hudson Atwell\Documents\Visual Studio\Projects\Test Project\Test Project]Windows\window_update.cs:line 125
我也要求以管理员身份运行该解决方案。
对我做错了什么有什么建议吗?
最佳答案
您传递的是一个目录名,而该方法需要一个文件名。尝试创建具有该名称的文件失败,因为已经存在具有该名称的目录。
关于c# - "could not find a part of the path"下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9899169/