C#Delete Files

Posted by someberry on Sat, 30 Nov 2019 08:13:43 +0100

When programming, one function is to save after drawing and then call display.But I often show the last saved picture directly the second time I use it. Later I found that deleting the last saved picture manually will display it correctly, so I used the C#Delete File feature so that I can delete the previous picture before saving it each time.

Functional implementation:

//Functions to Delete Files
        public static void DelectDir(string srcPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //Return all files and subdirectories in the directory
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //Determine whether folders
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //Delete subdirectories and files
                    }
                    else
                    {
                        File.Delete(i.FullName);      //Delete the specified file
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }

Since I know I need to delete files, I can simplify it to:

        public static void DelectDir(string srcPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //Return all files and subdirectories in the directory
                foreach (FileSystemInfo i in fileinfo)
                {                  
                        File.Delete(i.FullName);      //Delete the specified file
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }

Then call before saving the picture:

//Delete the file if it exists
if (Directory.Exists("a.gif"))
{
        DelectDir("a.gif");
}

Topics: Programming