Home > database >  C# FORM copy program crashes because of too much RAM usage
C# FORM copy program crashes because of too much RAM usage

Time:11-02

I've been trying to solve this problem, but I couldn't find a solution.

When I'm copying the RAM usage is more than 2gb or more and than my laptop freezes. What is can I do to free RAM?

This program sorts horizontal and vertical photoes so not a big deal and I'm aware that the code is not the best.

foreach (var srcPath in Directory.GetFiles(sourcePath))
        {
            
            string Name = Path.GetFileName(srcPath);
            //Gets the file's format (like png or jpeg)
            string ext = Path.GetExtension(srcPath);

            bool allowFile = false;

            //This line examines the correct file's format, if it's not correct it won't copy it.
            if (ext == ".png" || ext == ".jpeg" || ext == ".jpg" || ext == ".mp4" || ext == ".PNG" || ext == ".JPEG" || ext == ".JPG" || ext == ".MP4")
                allowFile = true;

            Image img = Image.FromFile(srcPath);

            int width = img.Width;
            int height = img.Height;
           

            if (allowFile)
            {
                if (height > width)
                {
                    File.Copy(srcPath, pathString   "\\"   Name , true);
                }
                else
                {
                    File.Copy(srcPath, pathString2   "\\"   Name, true);
                }
    
                //Copy the file from sourcepath and place into mentioned target path,                    
            }
        }

CodePudding user response:

You need to dispose of your image after using it, in order to free the used memory from the Image.FromFile call.

Try to wrap your image call in a using:

using (Image img = Image.FromFile(srcPath)) 
    {
        int width = img.Width;
        int height = img.Height;

        if (allowFile)
        {
            if (height > width)
            {
                File.Copy(srcPath, pathString   "\\"   Name , true);
            }
            else
            {
                File.Copy(srcPath, pathString2   "\\"   Name, true);
            }

            //Copy the file from sourcepath and place into mentioned target path,                    
        }
    }
  • Related