我正在处理一个项目,我尝试做的是删除 我文件夹中的文件。
但是我收到了错误:
Could not find part of the path.
问题是该路径有一个'确实构成了路径的一部分。这是我的代码:
foreach (var a in attachments)
{
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/Files/'"+ a.FileName +"'"));
foreach (string pathfile in files)
{
System.IO.File.Delete(pathfile);
}
}
结果路径是:
'C:..... \文件\' 14d75c4e-c25f-4288-9a75-08a359fe6d844.png'“
我该如何解决这个问题?
答案 0 :(得分:3)
您不需要单引号。
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/Files/"+ a.FileName));
答案 1 :(得分:2)
这是因为您的代码有额外的(不需要的)单引号。
....MapPath("~/Files/'"+ a.FileName +"'"));
更改此行;
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/Files/'"+ a.FileName +"'"));
到
string[] files = System.IO.Directory.GetFiles(Server.MapPath(string.Format("~/Files/{0}", a.FileName));
请注意代码段末尾的更改。
另外,如果我可以建议,请将其包装在Try / Catch
中(这将有助于将来调试)。
希望这有帮助。
答案 2 :(得分:0)
最后我解决了它。
问题是路径,我所做的事情很少 与以前不同。
我创建了一个返回根路径的方法。 然后我添加了一个简单的变量并执行 删除命令。
这是我的代码:
方式:强>
private string StorageRoot
{
get { return Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Files/")); }
}
删除命令:
foreach (var a in attachments)
{
var myfilename = a.FileName;
var filetoDelete = StorageRoot + myfilename;
System.IO.File.Delete(filetoDelete);
}
希望此解决方案可以帮助将来的某个人。