How to compress Video files in Windows Forms C#?

In this article, you will see video compression in Windows Forms C#.Here i have created sample project , so that you can understand clearly about what is happening during video compression in windows forms using C#.

My requirement is to compress video files.Here i am compressing avi files to MP4 files.Let us start creating console application in Visual Studio 2019.

Step 1: Create a Console Application in Visual Studio 2019


Step 2: Create a VideoCompression class.


Step 3: CompressVideos method of VideoCompression class.


Step 4: Calling VideoCompression class in Main entry point of Program class.


Step 5: Finally compile and run, you will see the console application window.


Step 6: For VideoCompression output you can view the path given in InputFile of CompressVideos method.

For more understanding,you can copy the below code directly and apply in your project.You will see the miracles.


    class Program
    {
        static void Main(string[] args)
        {
             string strEXEPath = string.Empty;
             string strParam = string.Empty;
            try
            {
              strEXEPath = @"D:\ffmpeg-4.4-full_build\bin\ffmpeg.exe";
              
                VideoCompression objvideocompress = new VideoCompression();
                objvideocompress.CompressVideos(strEXEPath);
              
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

    public class VideoCompression
    {
        public string CompressVideos(string exePath)
        {
            string result = String.Empty;         
            string inputfile = @"D:\samplevideo.avi";
            string outputfile = @"D:\VIDEOFILES\Output\output" + DateTime.Now.Ticks + ".mp4";
          
            using (Process p = new Process())
            {
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.FileName = exePath;
            
                p.StartInfo.Arguments = $"-i {inputfile} {outputfile}";
                // p.StartInfo.Arguments = parameters;
                p.Start();
                p.OutputDataReceived += (sender, line) =>
                {
                    if (line.Data != null)
                        Console.WriteLine(line.Data);
                };
                // p.WaitForExit();
                 if (!p.HasExited)
                {
                    // Discard cached information about the process.
                    p.CloseMainWindow();
                    // Free resources associated with process.
                    p.Close();
                    p.Dispose();
                    // Print working set to console.
                }
            }
            return result;
        }
    }