Home


.Net, SQL and softball. Musings of a software developer with a softball problem

Tuesday, May 26, 2009

Writing to a file with C#

It had been a while since I had to write a file with .Net, I don't think I really had done it since vanilla ASP. As I remember it wasn't hard then and it really hasn't changed to much since then. See below for code on how to check to see if the directory exists, and then how to actually create and write to a file.

Check to see if path exists if not create it

if(!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);

Create the file


public void WriteFile(string fileText, string fileName){
string fullPath = "<Where ever your path is>"

try{
FileInfo file = new FileInfo(fullPath);

StreamWriter stream = file.CreateText();
stream.WriteLine(fileText);
stream.Close();
}catch(Exception ex){
//handle exception
}
}

Labels:

posted by Tom Becker at

0 Comments:

Post a Comment

<< Home