This is my API method which uploads the .caf file to the server, converts into .mp3 and deletes the .caf file. But the problem is that both the original file and the converted file are being deleted instead of only the original file.
[HttpPost]
[ActionName("UploadCompetitionEntry")]
public async Task<HttpResponseMessage> UploadCompetitionEntry([FromUri]string folderName)
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
string path = System.Web.Hosting.HostingEnvironment.MapPath("~/" + folderName);
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(path);
var task = Request.Content.ReadAsMultipartAsync(provider);
// Log exceptions
await task.ContinueWith(t =>
{
if (t.IsFaulted)
{
// Log t.Exception
}
});
var bodyPart2 = provider.FileData.Where(p => p.Headers.ContentDisposition.Name.Replace("\"", string.Empty) == folderName).FirstOrDefault();
if (bodyPart2 != null)
{
string savedFile2 = bodyPart2.LocalFileName;
string originalFile2 = bodyPart2.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
string uniqueFilename = string.Format(@"{0}", Guid.NewGuid());
string newFile2 = uniqueFilename + Path.GetExtension(originalFile2);
// Copy file and rename with new file name and correct extension
FileInfo file2 = new FileInfo(savedFile2);
file2.CopyTo(Path.Combine(path, newFile2), true);
file2.Delete();
if (folderName == "music")
{
//converting .caf to .mp3 and creating a new .mp3 file
MediaFuncs.ConvertToMp3(Path.Combine(path, newFile2), uniqueFilename);
//deleting the .caf file
FileInfo file3 = new FileInfo(Path.Combine(path, newFile2));
file3.Delete();
}
}
return Request.CreateResponse(HttpStatusCode.OK, new ResponseMessage<Object> { success = true, message = "Media Uploaded" });
}
And this is my converter method
public static void ConvertToMp3(string filename, string uniqueFilename)
{
string musicPath = System.Web.Hosting.HostingEnvironment.MapPath("~/" + "music");
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
info.FileName = System.Web.Hosting.HostingEnvironment.MapPath("~/" + "ffmpeg.exe");
info.Arguments = " -i " + filename + " " + Path.Combine(musicPath, uniqueFilename + ".mp3");
System.Diagnostics.Process p1 = System.Diagnostics.Process.Start(info);
}
Am i doing something wrong? If anyone knows any other way to delete just the original file, please please let me know, i have been banging my head about it all day 🙁
EDIT: I put a breakpoint and checked. I think am deleting the .caf file before the conversion is complete. Because when i put the breakpoint just after calling the converter method and before deleting the file, the .mp3 wasnt deleted.
So now how do i stall the deleting till the conversion is complete?
You need to wait for the conversion to finish before deleting the source file.
To do that, you can simply call:
At the end of
ConvertToMp3.See
WaitForExiton MSDN.