| by kirupa  |  
					29 March 2007
 In the
					
					previous page, you learned what each line of code used 
					in our 'reading a file' example does. In this page, let's 
					learn about the other big part of this tutorial - writing 
					files. In this section, you will learn how to take string data and 
					write it to a file. While writing a file seems more 
					complicated, it actually takes fewer steps than when you are 
					reading a file.
 To write a file, all you really need to do is specify the 
					location of your saved file and have some text that you need 
					to write: 
						StreamWriter
						writer 
						= new
						StreamWriter("C:\\Users\\Kirupa\\Desktop\\foo.txt");
						writer.WriteLine("Hello 
						world!"); writer.Close(); Let's dive right into what the code actually does: 
 
						StreamWriter
						writer 
						= new
						StreamWriter("C:\\Users\\Kirupa\\Desktop\\foo.txt"); In this line, I create a new StreamWriter object called 
					writer. The StreamWriter constructor takes a file as an 
					argument. The file you specify is where your data will be 
					written to. If the file you specify does not exist, that 
					file will be created automatically for you. If the file 
					already exists, and no other program is currently accessing 
					it, you will overwrite it. 
 
						writer.WriteLine("Hello 
						world!"); In this line, you specify the text to write to your file. 
					The WriteLine method can take a string as its argument, and 
					in the above line, I am passing in the text "Hello World!" 
 
						writer.Close(); In this line, we commit the change we made by closing the 
					connection. If you do not close the StreamWriter object, any 
					text you write or modifications you make will not be saved. 
 As you can see, writing a line of text to a file is not 
					too complicated. The main thing to remember is that there is 
					no functionality to append data to the end of a file. Any 
					data you add overwrites the existing file with the new data, 
					so unless you want to lose your data, make sure to read and 
					store the existing data first. You cannot read a file that does not exist, and you 
					may not want to overwrite an existing file. Both of these 
					scenarios can be avoided by checking if the file you are 
					writing to exists first. You can check if a File exists by 
					using File.Exists(): 
						string
						filePath
						= 
						"C:\\Users\\Kirupa\\Desktop\\foo.txt");
						  if
						(File.Exists(filePath))
						{ 
							// File exists } else { 
							// File does not exist } In the
					
					next page, I will provide some more information 
					concerning checking how a file exists and wrap it up with a 
					brief discussion on the asynchronous properties of the 
					StreamReader and StreamWriter classes. Onwards to the
					
					next page! |