【问题标题】:File Gets Written In The First Condition Only文件仅在第一个条件下写入
【发布时间】:2017-04-09 12:49:49
【问题描述】:

我正在尝试写入一个文本文件,我的条件是如果该文件中已经存在写入,那么它应该打印“添加了另一行 - 消息”。所以我尝试了以下方法,但它抛出异常'它正在被另一个进程使用',我可以理解我做错了什么:

public void WriteMessage(string message)
{
   string path = @"C:\Users\AT\Documents\Visual Studio 2013\Projects\Sample_App\Sample_App\app_data\log.txt"; //File path

   FileStream stream;

   if (File.Exists(path))
   {
     stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); //This section used to read and write operations

     using (StreamWriter writer = new StreamWriter(stream)) //Writing words to the text file
     {
       string[] lines = File.ReadAllLines(path); //Here is the exception - It's being used by another process

        if (lines.Length > 0)
        {
           writer.WriteLine("\n" + "Another Line Added - " + message);
           writer.Flush();

           stream.Close();
        }
      }
    }
    else
    {
       /**If text file is created for the first time - Starts**/
       stream = new FileStream(path, FileMode.Create); //This section used to read and write operations

       using (StreamWriter writer = new StreamWriter(stream)) //Writing words to the text file
       {
          writer.WriteLine(message);
          writer.Flush();

          stream.Close();
       }
       /**If text file is created for the first time - Ends**/
    }
}

现在会发生什么情况,该文件是为第一个包含文本的 'Hello World!! 创建的,当我向其中添加另一个文本时,我期望得到以下输出:

预期输出:

世界你好!! ---- 只有第一次否则

添加了另一行 - Hello World!

添加了另一行 - Hello World!

添加了另一行 - Hello World!

我希望有一些想法或建议可以让它发挥作用,并让我知道我做错了什么。这完全是一个简单的。我想在文件中再做一件事,如下所示:

输出:

1) 你好世界!!

2) 你好世界!!

注意:在上面的输出中,每当我运行控制台应用程序时,我都会增加数字。这意味着如果存在相同的写入,那么它应该增加一。我期待一个简单的 Linq 能做到这一点,是否有可能以一种简单的方式做到:(在这种情况下,我是否需要创建任何模型来处理文本文件?)

var query = (var c in fileName
         select c);

foreach(var item in query)
{
  //Do something here
}

我已经完成了以下工作,但还无法完成上述工作:

MSDN - 01

MSDN - 02

【问题讨论】:

    标签: c# text-files


    【解决方案1】:

    File.ReadAllLines(path); 创建另一个流。

    将它放在 FileStream 上方应该可以修复它

    因为您使用的是using 关键字,所以您不必关闭流

    public static void WriteMessage(string message)
        {
            string path = @"log.txt"; //File path
    
            FileStream stream;
    
            if (File.Exists(path))
            {
                string[] lines = File.ReadAllLines(path);
                stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); //This section used to read and write operations
    
                using (StreamWriter writer = new StreamWriter(stream)) //Writing words to the text file
                {
                    if (lines.Length > 0)
                    {
                        writer.WriteLine("\n" + "Another Line Added - " + message);
                        writer.Flush();
                    }
                }
            }
            else
            {
                /**If text file is created for the first time - Starts**/
                stream = new FileStream(path, FileMode.Create); //This section used to read and write operations
    
                using (StreamWriter writer = new StreamWriter(stream)) //Writing words to the text file
                {
                    writer.WriteLine(message);
                    writer.Flush();
                }
                /**If text file is created for the first time - Ends**/
            }
        }
    

    【讨论】:

    • 放置并开始工作。谢谢。您能否简要介绍一下我试图在文本文件中加一的第二种方法?
    【解决方案2】:

    处理原始流是一种有效的文件处理方式,如果您及时返回的话。我们有更新的 .NET Framework 版本和更简单更好的文件处理功能:

    public void WriteMessage(string message)
    {
       string path = @"C:\Users\AT\Documents\Visual Studio 2013\Projects\Sample_App\Sample_App\app_data\log.txt"; //File path
    
       if (File.Exists(path))
       {
         File.AppendAllLines(path, new[]{ "Another line added - Hello world" });
       }
       else
       {
         File.AppendAllLines(path, new[]{ "Hello World!!" });
       }
    }
    

    实际考虑文件内容的示例:

    public void WriteMessageWithLineNumbers(string message)
    {
       string path = @"C:\Users\AT\Documents\Visual Studio 2013\Projects\Sample_App\Sample_App\app_data\log.txt"; //File path
    
       if (File.Exists(path))
       {
         var lines = File.ReadAllLines(path);
    
         var nextLine = string.Format("{0} - Hello World", lines.Length + 1)
    
         File.AppendAllLines(path, new[]{ nextLine });
       }
       else
       {
         File.AppendAllLines(path, new[]{ "1 - Hello World!!" });
       }
    }
    

    【讨论】:

    • 我搞定了。谢谢。您能否简要介绍一下我试图在文本文件中加一的第二种方法?
    • @AT-2016 添加了处理文件内容的第二个示例。
    • 好一个@nvoigt。这真的很容易使用。但我很想知道我是否以另一种方式尝试它,比如使用 Linq 来控制文本文件,使用模型或与之相关的任何东西是否明智?
    • @AT-2016 这个问题对于评论来说有点宽泛。 LinQ 用于查询(即 LinQ 中的 Q),而不是用于操作。您可以对结果进行操作,也可以作为 LinQ 语句的副作用(不好!)。也许你应该问另一个问题。
    【解决方案3】:

    StreamWriter 用于文本写入不需要构造函数的Stream 参数。它可以直接使用文件本身的路径。这样就可以省略FileStream:

        public static void WriteMessage(string message)
        {
            var path = @"../../sth.txt"; //File path
            if (File.Exists(path))
            {
                string[] lines = File.ReadAllLines(path);//This section used to read and write operations
                using (var writer = new StreamWriter(path, true)) //Writing words to the text file
                {
                    if (lines.Length > 0)
                    {
                        writer.WriteLine("Another Line Added - " + message);
                    }
                    else
                    {
                        writer.WriteLine(message);
                    }
    
                    writer.Flush();
                }
            }
            else
            {
                /**If text file is created for the first time - Starts**/
                using (StreamWriter writer = new StreamWriter(path)) //Writing words to the text file
                {
                    writer.WriteLine(message);
                    writer.Flush();
                }
                /**If text file is created for the first time - Ends**/
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      相关资源
      最近更新 更多