【问题标题】:DirectoryNotFoundException error while copying the file复制文件时出现 DirectoryNotFoundException 错误
【发布时间】:2014-05-31 12:13:22
【问题描述】:

我正在尝试开发一个将文件发送到服务器的 Web 应用程序(在这种情况下,服务器是本地服务器)。但是,当我尝试发送文件时,它总是给出:

DirectoryNotFoundException:找不到部分路径。

我已验证该文件夹确实存在。为了确保,我在复制之前创建了目录,但我仍然得到错误。有人可以帮忙吗? 代码如下:

string FileName = System.IO.Path.GetFileName("c:\\test\\Sample.txt");
string SaveLocation = HttpContext.Current.Server.MapPath("Uploadfile") + "\\";

if (System.IO.Directory.Exists(SaveLocation))
{
     System.IO.Directory.CreateDirectory(SaveLocation);
     System.IO.File.Copy("C:\\test\\Sample.txt", SaveLocation, true);
}

SaveLocation 的值为:

C:\Users\Nerd\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\Uploadfile\

【问题讨论】:

  • 复制文件时 SaveLocation 的确切值是多少?
  • 它是:“C:\Users\Nerd\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\Uploadfile\”。
  • 顺便说一句,使用这种语法string directory = @"c:\test\Sample.txt"; 编写这样的字符串通常更容易避免使用转义字符。
  • @David:我尝试使用它,但无济于事。
  • @nerd 抱歉,这不是一个答案,只是一个可以使字符串更具可读性的指针。

标签: c# asp.net web-applications


【解决方案1】:

System.IO.File.Copy 需要它的第二个参数是文件路径而不是目录路径。调整您的代码以包含您希望保存文件的名称。

string FileName = System.IO.Path.GetFileName("c:\\test\\Sample.txt");
string SaveLocation = HttpContext.Current.Server.MapPath("Uploadfile") + "\\";

if (System.IO.Directory.Exists(SaveLocation))
{
     System.IO.Directory.CreateDirectory(SaveLocation);
     System.IO.File.Copy("C:\\test\\Sample.txt", SaveLocation + "Sample.txt", true);
}

【讨论】:

  • 这是正确的,但它不会给DirectoryNotFoundException,它应该给IOException'和消息The target file "..." is a directory, not a file.
  • @DavidG 确实,在这种情况下,错误消息并没有真正的帮助
猜你喜欢
  • 2017-06-20
  • 2015-07-16
  • 1970-01-01
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2022-08-08
相关资源
最近更新 更多