I have an issue in my Web Api when I try to delete some files from the server, i get this error
"The process cannot access the file because it is being used by another process"
My delete method is called in this get method :
public IQueryable<FriendChallenge> GetJudgedChallenge(string id)
{
var friendChallenges = challengeFriendRepo.GetFriendJudgeChallenge(id);
var query = friendChallenges;
ChangeFriendChallenge(friendChallenges, "");
query.ForEach(fc => fc.Challenge = challengeRepo.Get(fc.ChallengeId));
query.ForEach(fc => fc.Friend = friendRepo.Get(fc.FriendId));
query.ForEach(fc => fc.Challenge.User.UserName = AESCrypt.DecryptRijndael(fc.Challenge.User.UserName, fc.Challenge.User.SecurityStamp));
deleteFile(friendChallenges);
return query.AsQueryable();
}
To be sure that i can delete the file, I have to call delete method from this get method.
So my delete method loop in my list and i get the filename to create the path :
string localFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\ChallengeContent\";
localFilePath += imagePath;
if (File.Exists(localFilePath))
{
// Content.Dispose();
File.Delete(localFilePath);
}
The file exist, but when the File.Delete is call i get the error...
All my Read method are done in a using, the write is a multipart method.
EDIT :
My write method :
public async Task<HttpResponseMessage> UploadFile()
{
// Check whether the POST operation is MultiPart?
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string appPath = AppDomain.CurrentDomain.BaseDirectory + @"\ChallengeContent\";
string fileName = String.Empty;
if (Directory.Exists(appPath) == false)
{
Directory.CreateDirectory(appPath);
}
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(appPath);
List<string> files = new List<string>();
try
{
// Read all contents of multipart message into and save files in the server
await Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
}
// Send OK Response along with saved file names to the client.
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
EDIT 2 :
Sorry I did not think to add it with in the previous edit
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
/// <summary>
/// multipart provider
/// </summary>
/// <param name="path">path</param>
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
/// <summary>
/// Get local file name multipart
/// </summary>
/// <param name="headers">http header</param>
/// <returns>file name</returns>
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}