【问题标题】:Why it copies before writing? [closed]为什么要先复制再写? [关闭]
【发布时间】:2021-07-24 16:07:29
【问题描述】:
public void AddFile()
    {
        Console.Write("What file to add? : ");
        string fileName = Console.ReadLine();
        pathString = Path.Combine(FolderName, MainFolder,fileName);
        
        using StreamWriter file = new(pathString, append: true);
        file.Write("hello world");
        
        
        string source = Path.Combine(FolderName, MainFolder, fileName);
        string dest = Path.Combine(FolderName, SyncFolder, fileName);
        File.Copy(source,dest,true); 
    }

为什么代码的最后一行会在我的 file.Write("hello world") 之前(或者至少是这样)复制文件?
首次启动:主文件夹中的文件有“hello world”。同步文件夹中的文件为空
首次启动:主文件夹中的文件有“hello world”x2。 Sync文件夹中的文件只有一个“hello world”
我该如何解决?

【问题讨论】:

标签: c#


【解决方案1】:

这是因为您声明的using 变量导致StreamWriter 一直打开到函数结束,也就是写入文件时。您必须将其更改为以下内容:

using (StreamWriter file = new(pathString, append: true))
    file.Write("hello world");

这样,当using 块超过StreamWriter 写入文件时,文件将在文件被复制之前被写入。

【讨论】:

    【解决方案2】:

    删除using 行并将file.Write 替换为

    File.AppendAllText(pathString, "hello world");
    

    以后要注意这三件事的区别:

    经典using多行块(定义范围)

    using (var x = new SomeDisposableThing()) {
      using (var y = new OtherDisposableThing()) {
        //x and y are in scope for this 
        //entire block until the
        //next curly bracket below
      }
      //x is in scope, y is disposed
    }
    

    经典using单行形式

    using (var x = new SomeDisposableThing()) 
      using (var y = new OtherDisposableThing()) 
        //x and y  in scope for this line only 
    //x and y not in scope now and have been disposed
    

    现代“扩展范围”using

    using var x = new SomeDisposableThing();
    using var y = new OtherDisposableThing();
    //x and y in scope for this 
    //entire current block
    //perhaps all the way to
    //the curly bracket that ends
    //the method
    

    后一种形式旨在使代码更具可读性,而不会出现大量缩进(当您执行数据库工作时,您可能会using 连接,然后是命令,然后是命令为您提供的适配器......它很多缩进),但你必须注意变量在被释放之前的生存时间

    因为您的变量一直存在到方法结束,然后被释放,所以您附加的数据很可能在您复制文件时没有刷新到文件中;之后就被刷新了

    如果你有一个一次性的创建/写入/追加的目标,则使用 File.XxxText 方法 - 如果你有一些持久的需要重复写入文件超过一定数量,请使用你保留的流写入器时间,但如果它是一次性的,那么那些衬里是方便的辅助方法

    【讨论】:

      猜你喜欢
      • 2019-10-29
      • 2021-06-12
      • 2014-09-24
      • 2014-08-25
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      相关资源
      最近更新 更多