Reputation: 4974
im working on a project and what i try to do is to delete the files in my folder.
but I get the error:
Could not find part of the path.
The problem is that the path have a ' which does make part of the path. Here is my code:
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);
}
}
the result path is this:
'c:.....\Files\'14d75c4e-c25f-4288-9a75-08a359fe6d844.png'"
How can I solve this?
Upvotes: 0
Views: 15349
Reputation: 4974
Finally i have solved it.
the problem was the path and what i have done was little different what i had before.
i have create a method to return the root path. And then i have add it a simple variable and execute the delete command.
Here is my code:
Method:
private string StorageRoot
{
get { return Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Files/")); }
}
Delete Command:
foreach (var a in attachments)
{
var myfilename = a.FileName;
var filetoDelete = StorageRoot + myfilename;
System.IO.File.Delete(filetoDelete);
}
Hope this solution helps someone in the future.
Upvotes: 0
Reputation: 4221
This is because your code has extra (un needed) single quotes.
....MapPath("~/Files/'"+ a.FileName +"'"));
Change this line;
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/Files/'"+ a.FileName +"'"));
to
string[] files = System.IO.Directory.GetFiles(Server.MapPath(string.Format("~/Files/{0}", a.FileName));
Notice the change at the end of the code snippet(s).
Also, if I could suggest, wrap this in a Try / Catch
(this would will help any future debugging as well).
Hope this helps.
Upvotes: 2
Reputation: 32721
You don't need single quotes.
string[] files = System.IO.Directory.GetFiles(Server.MapPath("~/Files/"+ a.FileName));
Upvotes: 3