【问题标题】:how to save text in textbox in flatfile?如何在平面文件的文本框中保存文本?
【发布时间】:2016-02-10 18:19:03
【问题描述】:

我使用 GUI 开发了一个 C# 应用程序,并在文本框中保留了一些日志。当用户单击保存按钮时,文件夹浏览器对话框打开。用户选择一个目录并单击确定。 MessageBox 出现,包括“保存到文件...”的消息。操作完成。

我说的这些都发生了,但是 目录中没有文件 用户指定的。 当我既没有使用 TextWriter 对象,也没有使用 File.WriteAllText(..),我总是失败。下面的代码有问题吗?

private void saveBtn_Click(object sender, EventArgs e)
    {
        if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
        {
            // create a writer and open the file
            TextWriter tw = new StreamWriter(folderBrowserDialog.SelectedPath + "logFile.txt");
            // write a line of text to the file
            tw.WriteLine(histTxt.Text);
            // close the stream
            tw.Close();

            //File.WriteAllText(folderBrowserDialog.SelectedPath + "logFile.txt", histTxt.Text);
            MessageBox.Show("Saved to " + folderBrowserDialog.SelectedPath + "\\logFile.txt", "Saved Log File", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

【问题讨论】:

  • 如果你不指定文件夹位置,你会让文件出现吗?
  • 查找一个文件夹 - 根据消息框,您似乎正在将其写入 c:\some\pathlogfile.txt,而不是 c:\some\path\logfile.txt。你可能想看看Path.Combine
  • new StreamWriter(folderBrowserDialog.SelectedPath + "logFile.txt"); 中缺少反斜杠?

标签: c#


【解决方案1】:

使用Path.Combine 创建/添加文件路径,如下所示:

        TextWriter tw = new StreamWriter(Path.Combine(folderBrowserDialog.SelectedPath, "logFile.txt"));

如果需要,这将添加当前操作系统的路径分隔符。

【讨论】:

    【解决方案2】:

    在创建流时,请使用 using 子句自动释放资源。如果您想创建文件:

    using (FileStream fs = File.Create(path)) 
        using (TextWriter tw = new StreamWriter(fs))
        {
           tw.WriteLine(histTxt.Text);
           tw.Close();
        }
    

    该代码应该可以工作,并释放 File.Create 方法在文件上创建的锁。

    【讨论】:

      猜你喜欢
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 2023-01-21
      相关资源
      最近更新 更多