【问题标题】:How can I check if this file name is created or not in c# [duplicate]如何检查此文件名是否在c#中创建[重复]
【发布时间】:2016-07-21 21:19:56
【问题描述】:

我正在尝试创建一个方法来检查是否创建了此文件 (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)
        {

        }

    }

【问题讨论】:

  • 试试File.Exists(path)
  • 请不要这样做catch (Exception ex) - 这是一种不好的做法,只会隐藏错误。如果您认为可以抛出异常并且可以有意义地处理它,那么只捕获该特定异常
  • 将标题复制并粘贴到 Google 会返回 File.Exists
  • 谜团是对的。如果文件存在,File.Exist(path) 将返回 bool == true。我很惊讶您无需发布问题就无法在其他地方找到此问题。使用简单的谷歌搜索应该有大量的文档。您应该知道的一件事是您必须使用完整的路径名。此外,您需要通过双斜杠来转义斜杠,或者您可以在字符串的开头添加一个“@”符号,这将告诉它按字面意思处理转义字符。
  • 正如其他人所指出的,这个答案可以通过简单的搜索在网上轻松找到。

标签: c#


【解决方案1】:

您可以使用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 类及其方法的更详细说明。

【讨论】:

  • @Upvoters,你认为这段代码是如何工作的。一个条件是写,另一个是读。如果您是编码员,您将如何使用 fileStream 顺便说一句:File.Exists 建议在答案前 15 分钟使用,这不会为该评论增加任何价值......
  • File.Exists 只是 OP 寻求的答案的一部分。
  • 你的代码还是有问题,你在System.IO.File.Create(path);之后丢失了文件指针你不能再写这个文件了,因为它仍然是打开的:)
  • Nkosi,这是你的答案......我只说你的代码不正确......如何更正是你的问题。如果您不知道,请不要发布答案.....
  • @Eser 注意到并理解。只是想帮忙。这就是我认为该网站的全部意义所在。
猜你喜欢
  • 2018-10-29
  • 2015-09-05
  • 2018-11-23
  • 2015-07-19
  • 2013-11-30
  • 2012-01-25
  • 1970-01-01
  • 2010-09-30
相关资源
最近更新 更多