Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# winForms Outputting to Text File

Tags:

c#

winforms

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!

like image 230
Simagen Avatar asked Dec 25 '10 00:12

Simagen


2 Answers

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.

like image 76
Mathias Lykkegaard Lorenzen Avatar answered Oct 06 '22 01:10

Mathias Lykkegaard Lorenzen


How about...

String YourFormattedText = FieldFromForm.ToString( whatever formatting );
File.WriteAllText( FullPathAndFileNameToWriteTo, YourFormattedText );
like image 35
DRapp Avatar answered Oct 05 '22 23:10

DRapp