我使用Visual Studio 2013和C#从一个文本框以用户输入来创建一个文本文件名
我现在有一个形式,在其他项目中,有用户输入ID号码的文本。我希望能够'取得'这个号码并创建一个ID号为文件名的文本文件。
我已经能够使用OpenFileDialog和Streamwriter写入文件,但这需要用户单击“保存位置”按钮并浏览到文件位置,然后输入他们想要创建的文件的文本。
我宁愿让程序根据ID号创建.txt文件,以便他们可以输入他们的ID,然后按回车键启动程序。
这可能吗?
我使用Visual Studio 2013和C#从一个文本框以用户输入来创建一个文本文件名
我现在有一个形式,在其他项目中,有用户输入ID号码的文本。我希望能够'取得'这个号码并创建一个ID号为文件名的文本文件。
我已经能够使用OpenFileDialog和Streamwriter写入文件,但这需要用户单击“保存位置”按钮并浏览到文件位置,然后输入他们想要创建的文件的文本。
我宁愿让程序根据ID号创建.txt文件,以便他们可以输入他们的ID,然后按回车键启动程序。
这可能吗?
是的,这是可能的,这是微不足道的。如果您想使用您的StreamWriter
,只需将我的File.WriteAllText
替换为您的StreamWriter
代码即可。
button_click_handler(fake args)
{
string fileName = MyTextBox.Text;
File.WriteAllText(basePath + fileName, "file contents");
}
所以这将创建文件,如果它不存在,并添加到它,如果它不? – smokeAndMirrors
@smokeAndMirrors它覆盖文件,如果它在那里。它只是写无论如何。 – evanmcdonnal
当然这是可能的。在你的问题中唯一不清楚的地方就是你想创建这个文本文件的位置以及你想要在其中存储什么。
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");
}
我认为你可以找到非常有用的看着这个MSDN网页约Common I/O Tasks
有很多方法可以做到这一点。
string thepath = String.Format("{0}{1}{2}","C:\\PutDestinationHere\\",idTextBox.text,".txt");
using(StreamWriter writer = new StreamWriter(thepath))
{
writer.WriteLine();
}
这样的事情? http://stackoverflow.com/questions/9907682/create-a-txt-file-if-its-not-exist-and-if-it-exist-write-a-line-with-c-sharp – Goose
什么@鹅说。如果您希望他们选择一个文件夹(但仍自动创建文件名),请查看[FolderBrowserDialog](http://msdn.microsoft.com/zh-cn/library/system.windows.forms.folderbrowserdialog %28V = vs.110%29.aspx)。 – admdrew
谢谢@Goose在发布我的问题之前,我想我已经搜索了其他答案。答案的一部分肯定有助于我的查询。 – smokeAndMirrors