c#winForms输出到文本文件

时间:2010-12-25 00:55:33

标签: c# winforms

我在visual studio 2010中使用C#windows Forms。

我需要知道将在winForm中选择的数据输出到一个简单的文本文件中的最佳方法是什么?

一个例子:

用户必须选择时间/日期。用户选择后,再点击确认。

我需要winForm中的确认按钮将日期/时间发送到保存在给定位置的计算机上的txt文件。

非常感谢这方面的任何帮助!

2 个答案:

答案 0 :(得分:5)

使用System.IO.StreamWriter。

举个例子:

System.IO.StreamWriter writer = new System.IO.StreamWriter("path to file"); //open the file for writing.
writer.Write(DateTime.Now.ToString()); //write the current date to the file. change this with your date or something.
writer.Close(); //remember to close the file again.
writer.Dispose(); //remember to dispose it from the memory.

如果您在写入文件时遇到问题,可能是由于UAC(用户帐户控制)阻止了对该特定文件的访问。典型的解决方法是以管理员身份启动程序以防止这种情况发生,但我发现这是一个相当糟糕的解决方案。

此外,将数据存储在文档文件夹中对用户来说是令人不愉快的。一些用户(包括我自己)喜欢将我的文档文件夹保存为......文档,而不是应用程序设置和配置文件。

因此,我建议使用Local Application Data文件夹(如果在开始菜单搜索字段中键入%localappdata%,则会找到该文件夹​​)。 UAC未锁定此文件夹,也不需要管理权限写入。它实际上就是为了这个目的;存储设置和数据。

可以使用以下命令返回此目录的路径:

string path = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

我希望这能回答你的问题。

答案 1 :(得分:2)

怎么样......

String YourFormattedText = FieldFromForm.ToString( whatever formatting );
File.WriteAllText( FullPathAndFileNameToWriteTo, YourFormattedText );