I am using C# windows Forms in visual studio 2010.
I need to know what the best way at going about outputting data that has been selected in a winForm, into a simple text file would be please?
An Example:
The user has to select a time/date. once the user selects it, they then click confirm.
i need the confirm button in the winForm to send the date/time to a txt file that is saved onto the computer at a given location.
any help in this area will be much appreciated!
Use the System.IO.StreamWriter.
As an example:
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.
If you have issues writing to the file, it may be due to UAC (User Account Control) blocking access to that specific file. The typical workaround would be to launch the program as an administrator to prevent this from happening, but I find that to be a rather bad solution.
Also, storing data in the documents folder is unpleasant for the user. Some users (including myself) like to keep my documents folder full of... documents, and not application settings and configuration files.
Therefore, I suggest using the Local Application Data folder (found if you type %localappdata% in the start menu search-field). This folder is not locked by UAC, and will not require administrative priviledges to write to. It is actually meant for exactly this purpose; storing settings and data.
The path to this directory can be returned using:
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
I hope this answers your question.
How about...
String YourFormattedText = FieldFromForm.ToString( whatever formatting );
File.WriteAllText( FullPathAndFileNameToWriteTo, YourFormattedText );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With