I have a small upload application where i upload a file using a webservice (asmx), check the MD5 and verify it. Problem is that when i verify the file it says that the file is locked by another process. Below is my code for uploading and verifying:
private static object padlock = new object();
Chunking the upload file in smaller bites and uploading each of them
[WebMethod]
public void LargeUpload(byte[] content, string uniqueName)
{
lock (padlock)
{
string path = Server.MapPath(PartialDir + "/" + uniqueName);
BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Append, FileAccess.Write));
writer.Write(content);
writer.Flush();
writer.Close();
writer = null;
}
}
After the last one insert it into my database. After this the client verifies the file by requesting the MD5:
[WebMethod]
public int EndLargeUpload(string name, int folderId, long length, string uniqueName, int customerid)
{
lock (padlock)
{
string path = Server.MapPath(PartialDir + "/" + uniqueName);
string newPath = Server.MapPath(RepositoryDir + "/" + uniqueName);
File.Copy(path, newPath);
//delete partial
File.Delete(path);
string extension = Path.GetExtension(uniqueName);
string newFileName = uniqueName;
GWFile newFile = new GWFile();
newFile.DiscName = newFileName;
newFile.FileName = name;
newFile.FolderId = folderId;
newFile.Description = "";
newFile.Size = (int)length;
newFile.DiscFolder = Server.MapPath("/Repository");
newFile.DiscRelativePath = "/Repository/" + newFile.DiscName;
newFile.CustomerId = customerid;
IGWFileRepository fileRepository = ObjectFactory.GetInstance<IGWFileRepository>();
fileRepository.SaveFile(newFile);
return newFile.Id;
}
}
After the EndLargeUpload() method the client calls the RequestMD5 method with the id of the file, this call excepts with an exception that it cannot open the file “…..xxx…” because it s being used by another process…
private string GetMD5HashFromFile(string fileName)
{
lock (padlock)
{
using (FileStream file = new FileStream(fileName, FileMode.Open)) // <-- excepts here
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
}
}
I used the process explorer from sysinternals to view the file, it says that the file is locked by the web server ( pls refer to this img: http://screencast.com/t/oqvqWXLjku) – how can the web server lock it? can I work around this?
Switched to IIS, and the problem seems to go away…