Andrew Simpson
Andrew Simpson

Reputation: 7314

Cannot access the file because it is being used by another process using ffmpeg

I am getting the error:

Cannot access the file because it is being used by another process

I have a C# desktop app.

I am using the Process class to convert images to a video file by using FFMPEG.

This is my code:

using (Process serverBuild = new Process())
{
    serverBuild.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
    string args = " -f image2  -i " + {path} + "\\img%05d.jpg -s 352x288  -filter:v \"setpts=5.0*PTS\" -y " + {path}\\File.mp4;

    serverBuild.StartInfo.Arguments = args;
    serverBuild.StartInfo.FileName = "ffmpeg.exe";
    serverBuild.StartInfo.UseShellExecute = false;
    serverBuild.StartInfo.RedirectStandardOutput = true;
    serverBuild.StartInfo.RedirectStandardError = true;
    serverBuild.StartInfo.CreateNoWindow = true;
    serverBuild.Start();
    //  string output = serverBuild.StandardOutput.ReadToEnd();
    //Log.Instance.Debug(serverBuild.StandardError.ReadToEnd());
    serverBuild.WaitForExit();
    serverBuild.Close();

}

 Directory.Delete(ExportRoute + FFMPEGPacket.LicenseKey + "\\" + FFMPEGPacket.Guid, true);

//which raise the error..

The images are all deleted but the File.Mp4 is not and that is the error. The error says that the newly created MP4 file cannot be deleted.

NB This is partial code to illustrate the error

Upvotes: 2

Views: 1503

Answers (3)

Ahmad
Ahmad

Reputation: 9658

You may try the following code to create the file (it worked for me):

        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = exe_path;
        // replace your arguments here
        psi.Arguments = string.Format(@" arguments ") 

        psi.CreateNoWindow = true;
        psi.ErrorDialog = true;
        psi.UseShellExecute = false;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardInput = false;
        psi.RedirectStandardError = true;
        Process exeProcess = Process.Start(psi);
        exeProcess.PriorityClass = ProcessPriorityClass.High;
        string outString = string.Empty;
        exeProcess.OutputDataReceived += (s, e) =>
        {
            outString += e.Data;
        };
        exeProcess.BeginOutputReadLine();
        string errString = exeProcess.StandardError.ReadToEnd();
        Trace.WriteLine(outString);
        Trace.TraceError(errString);
        exeProcess.WaitForExit();
        exeProcess.Close();
        exeProcess.Dispose();

Upvotes: 2

ken lacoste
ken lacoste

Reputation: 894

FFMPEG might still be rendering the creation of video from images after it closes, so it might be worth if you place a Threading.Thead.Sleep(5000) 5 secs; before delete.

Upvotes: 2

Orkun Bekar
Orkun Bekar

Reputation: 1441

Try that:

File.WriteAllBytes(path, new byte[0]);
File.Delete(path);

Upvotes: 0

Related Questions