如果文件不存在,请继续

时间:2016-01-26 18:26:22

标签: c# io

我有以下代码:

public static void readtext(string pathtoText)
{

    if (File.Exists(pathtoText))
    {   
        string[] lines = System.IO.File.ReadAllLines(pathtoText);

        // Display the file contents by using a foreach loop.
        foreach (string line in lines)
        {
            clearPath(line);
        }
    }
    else
    {
        Console.WriteLine("{0} doesn't exist, or isn't a valid text file", pathtoText);
    }
}

public static void clearPath(string path)
{

    if(Directory.Exists(path))
    {
        int directoryCount = Directory.GetDirectories(path).Length;

        if(directoryCount > 0)
        {
            Console.WriteLine("{0} has Subdirectories to Remove", path);
            DirectoryInfo di = new DirectoryInfo(path);

            foreach (DirectoryInfo dir in di.GetDirectories())
            {
                dir.Delete(true); 
            }
        }
        else
        {
            Console.WriteLine("{0} has no directories to remove", path);
        }

        int fileCount = Directory.GetFiles(path).Length;

        if (fileCount > 0)
        {
            Console.WriteLine("{0} has files to Remove", path);

            System.IO.DirectoryInfo di = new DirectoryInfo(path);

            foreach (FileInfo file in di.GetFiles())
            {
                try
                {
                    file.Delete(); 
                }
                catch(System.IO.IOException)
                {
                    Console.WriteLine("Please Close the following File {0}", file.Name);
                }
            }
        } 
    }
    else
    {
        Console.WriteLine("Path Doesn't Exist {0}", path);
    }
}

我的函数从文本文件中读取目录并将其传递给clearPath,以检查目录是否存在,如果存在,则清除它。我的问题是,如果目录不存在,它会停止程序(它不会移动到下一个目录来检查它是否存在并清理,每个循环都停止)。

即使特定目录不存在,如何将其转到下一个目录?

1 个答案:

答案 0 :(得分:-1)

您的文件中可能有空行?

你可以尝试这样的事情:

foreach (string line in lines)
{
    if (!String.IsNullOrWhiteSpace(line))
    {
      clearPath(line.trim());
    }
}