从文本框中获取用户输入以创建文本文件名

时间:2014-01-23 22:28:50

标签: c# winforms textbox streamwriter

我正在使用Visual Studio 2013和C#

我目前有一个表单,除其他项目外,还有一个文本框供用户输入ID号。我希望能够“获取”这个数字并创建一个文本文件,其ID号作为文件名。

我已经能够使用OpenFileDialog和Streamwriter写入文件,但这需要用户单击“保存位置”按钮并浏览到文件位置,然后输入他们想要创建的文件的文本。 / p>

我希望程序根据ID号创建.txt文件,这样他们就可以输入他们的ID,然后按Enter键启动程序。

这可能吗?

3 个答案:

答案 0 :(得分:1)

是的,这是可能的,这是微不足道的。如果您想使用StreamWriter,只需将File.WriteAllText替换为您的StreamWriter代码。

button_click_handler(fake args)
{
     string fileName = MyTextBox.Text;
     File.WriteAllText(basePath + fileName, "file contents");
}

答案 1 :(得分:1)

当然有可能。您的问题中唯一不明确的一点是您要在哪里创建此文本文件以及您要在其中存储的内容。

 string fileName = txtForFileName.Text;
 // create a path to the MyDocuments folder
 string docPath = Environment.GetFolderPath(Environment.SpecialFolders.MyDocuments);
 // Combine the file name with the path
 string fullPath = Path.Combine(docPath, fileName);

 // Note that if the file exists it is overwritten
 // If you want to APPEND then use: new StreamWriter(fullPath, true)
 using(StreamWriter sw = new StreamWriter(fullPath))
 {
    sw.WriteLine("Hello world");
 }

我认为您可以找到有关Common I/O Tasks

的MSDN页面非常有用的内容

答案 2 :(得分:0)

有很多方法可以做到这一点。

 string thepath = String.Format("{0}{1}{2}","C:\\PutDestinationHere\\",idTextBox.text,".txt");

 using(StreamWriter writer = new StreamWriter(thepath))
  {
     writer.WriteLine();
  }