我正在做一个项目,我想要做的是删除文件夹中的文件。
但我知道错误是:
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:.....\Files\'14d75c4e-c25f-4288-9a75-08a359fe6d844.png'“
我怎么才能解决这个问题?
发布于 2013-09-30 14:47:55
我终于把它解决了。
问题在于我所走的路,我所做的与我以前所做的几乎没有什么不同。
我创建了一个返回根路径的方法。然后,我添加了一个简单的变量并执行delete命令。
这里是我的代码:
方法:
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);
}希望这个解决方案能对将来的人有所帮助。
发布于 2013-09-30 11:47:26
你不需要单引号。
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/Files/"+ a.FileName));发布于 2013-09-30 12:51:27
这是因为您的代码有额外的(不需要)单引号。
....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 (这也将有助于任何未来的调试)。
希望这能有所帮助。
https://stackoverflow.com/questions/19093175
复制相似问题