【问题标题】:Writing to a text file with a variable for the name使用名称变量写入文本文件
【发布时间】:2013-10-12 20:04:21
【问题描述】:

好的,所以我的问题是;我正在尝试将文件保存到 C: 驱动器的文件夹中。现在,我知道如何对像

这样的常规文件执行此操作
using(StreamWriter writer = new SteamWriter("c:\\Folder\\TextFile.txt");

我一直在想的是如何做到这一点,以便将文本文件的名称替换为变量,所以它更像

using(StreamWriter writer = new SteamWriter("c:\\Folder\\Variablegoeshere.txt");

有没有我可以做到这一点?

我为我糟糕的提问技巧道歉。

【问题讨论】:

  • 为什么人们会回答这种问题...
  • 我们为什么不呢,@zinking?初学者有一个问题。这个问题并不罕见,真的。

标签: c# streamwriter


【解决方案1】:

StreamWriter 构造函数与许多其他构造函数和方法调用一样,采用字符串参数。你可以传递任何你喜欢的字符串。在您的第一个代码示例中,您向构造函数传递了一个“字符串文字”——一个具有常量值的未命名字符串变量。相反,您可以传递一个预先构建的标准字符串变量。例如:

string name = // whatever you like
string path = "c:\\Folder\\" + name + ".txt"; // use '+' to combine strings
using (StreamWriter writer = new SteamWriter(path));

我通常喜欢在连接路径组件时使用Path.Combine 静态方法。帮助我避免丢失或加倍反斜杠的问题:

string path = System.IO.Path.Combine("c:\\Folder", name + ".txt");

最后,使用string verbatim modifier,您可以避免那些丑陋的双反斜杠,否则这是必要的,因为反斜杠是非逐字字符串中的“转义”字符:

string path = System.IO.Path.Combine(@"c:\Folder", name + ".txt");

这里是 Microsoft developer reference page for strings in C#。值得一读,更大的C# language reference

【讨论】:

    【解决方案2】:
    var inputPath = "c:\\Folder\\TextFile.txt";
    var folderPath = Path.GetDirectoryName( inputPath );
    using ( var writer = new StreamWriter ( Path.Combine( folderPath, "Variablegoeshere.txt" ) )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2018-01-01
      • 2019-05-12
      相关资源
      最近更新 更多