当我尝试从服务器删除某些文件时,我的Web Api出现问题,我收到此错误
“进程无法访问该文件,因为它正在被使用 另一个过程“
我的删除方法在此get方法中调用:
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();
}
为了确保我可以删除该文件,我必须从这个get方法调用delete方法。
所以我的删除方法循环在我的列表中,我得到文件名来创建路径:
string localFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\ChallengeContent\";
localFilePath += imagePath;
if (File.Exists(localFilePath))
{
// Content.Dispose();
File.Delete(localFilePath);
}
该文件存在,但是当调用File.Delete时,我收到错误...
我的所有Read方法都是在使用中完成的,write是一个多部分方法。
编辑:
我的写法:
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);
}
}
编辑2:
抱歉,我不想在之前的编辑中添加它
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);
}
}