如何在c#中检查是否创建了此文件名

时间:2016-04-01 22:48:09

标签: c#

我试图创建一个方法来检查是否创建了这个文件(todayfile.txt),如果不是我需要它来创建它。这就是我的想法:

private void ReadWater()
    {
        try
        {
            StreamReader inputFile;

            // I want to check if there is a file named ( Todayfile.txt )

            if (// if this file ( Todayfile.txt) is founded)
            {
                // Do this
            }

            else // if there is no file in this nmae ( Todayfile.text )
            {
                // create a new file 
            }

        }
        catch (Exception ex)
        {

        }

    }

1 个答案:

答案 0 :(得分:0)

您可以使用System.IO.File类来检查和创建文件。

以下示例演示如何使用File类检查文件是否存在,并根据结果创建新文件并写入文件,或打开现有文件并从中读取。

private void ReadWater()
{
    string path = "Todayfile.txt";
    // if there is no file in this name ( Todayfile.txt )
    if(!System.IO.File.Exists(path)) {
        // Create a file to write to.
        using (StreamWriter sw = File.CreateText(path)) {
            sw.WriteLine("Hello");
            sw.WriteLine("And");
            sw.WriteLine("Welcome");
        }
    }
    //at this point file should exist.

    // Open the file to read from.
    using (StreamReader sr = File.OpenText(path)) {
        string s = "";
        while ((s = sr.ReadLine()) != null) {
            Console.WriteLine(s);
        }
    } 
}

检查上面提供的链接,以获得有关System.IO.File类及其方法的更详细说明。