Follow
Publications: 77 | Followers: 0

File I_O In C# - faculty.cascadia.edu

Publish on Category: Birds 0

File Output
Writing data out to a file
1
Output to files
StreamWriter: An object in theSystem.IOnamespace that lets you print output to a destination such as a file.Any methods you have used onConsole.out(such asWrite,WriteLine) will work on aStreamWriter.Syntax:StreamWritername= newStreamWriter( "file name" );Example:StreamWriteroutput = newStreamWriter( "out.txt" );output.WriteLine("Hello, file!");output.WriteLine("This is a second line of output.");output.Dispose();If you don’t call .Dispose() then C# will not write the data to the file
2
Output to files
Example:StreamWriteroutput = newStreamWriter( "out.txt" );output.WriteLine("Hello, file!");output.WriteLine("This is a second line of output.");output.Dispose();If you don’t call .Dispose() then C# will not write the data to the fileYou can use the ‘using’ construct, similar to the input slides:using(StreamWriteroutput = newStreamWriter("out.txt")){output.WriteLine("Hello, file!");output.WriteLine("This is a second line of output.");} //output.Dispose() called here automatically// This is C#-specificWe’lluse the .Dipose() pattern in these slides (so you’re used to it)
3
Details aboutStreamWriter
StreamWritername= newStreamWriter( "filename" );If the given file does not exist, it is created.If the given file already exists, it is overwritten.The output you print appears in a file, not on the console.You will have to open the file with an editor to see it.Do not open the same file for both reading(StreamReader)and writing (StreamWriter) at the same time.You will overwrite your input file with an empty file (0 bytes).
4
Console.OutandStreamWriter
The console output object,Console.Out,is aTextWriter.TheStreamWriterclass is a subclass of theTextWriterclass.TextWriterout1 =Console.Out;TextWriterout2 = newStreamWriter( "data.txt" );out1.WriteLine("Hello, console!");// goes to consoleout2.WriteLine("Hello, file!");// goes tofileout2.Dispose();A reference toConsole.Outcan be stored in aTextWritervariable.Printing to that variable causes console output to appear.You can passConsole.outto a method as aTextWriter.Allows a method to send output to the console or a file.
5
Hours question
Given a filehours.txtwith the following contents:123 Kim 12.5 8.1 7.6 3.2456 Eric 4.0 11.6 6.5 2.7 12789Stef8.0 8.0 8.0 8.0 7.5Task: computehours worked by eachpersonSend the outputto the filehours_out.txt.The program will produce no console output.But the filehours_out.txtwill be created with the text:Kim (ID#123) worked 31.4 hours (7.85 hours/day)Eric (ID#456) worked 36.8 hours (7.36 hours/day)Stef(ID#789) worked 39.5 hours (7.9 hours/day)
Hoursanswer
public voidSlide_8(){char[] delimiters = { ' ', '\t' };TextReaderinput = newStreamReader("Files/hours.txt");StreamWriteroutput = newStreamWriter("Files/hours_out.txt");StringsLine;while ((sLine=input.ReadLine()) != null){string[]tokensFromLine=sLine.Split(delimiters,StringSplitOptions.RemoveEmptyEntries);if (tokensFromLine.Length< 3){Console.WriteLine("Line contained fewer than 3 tokens! {0}",sLine);continue; // get next line}
7
Hoursanswer
intID;if (false == Int32.TryParse(tokensFromLine[0], out ID)){Console.WriteLine("Line did not start with ID number! {0}",sLine);continue; // get next line}string name =tokensFromLine[1];double sum = 0.0;intcount = 0;for (inti = 2; i <tokensFromLine.Length; i++){doubledNum;if (Double.TryParse(tokensFromLine[i], outdNum)){sum +=dNum;count++;}}
8
Hoursanswer
if( count == 0 ) // didn't find any hours worked{Console.WriteLine("Line did not find any hours worked! {0}",sLine);continue; // get next line}double average = sum / count;output.WriteLine("{0} (ID#{1}) worked {2} hours ({3} hours/day)", name, ID, sum, average);// If you changeoutput.WriteLinetoConsole.WriteLine// you’d see the output on the screen}output.Dispose();}
9
Credits
The Chapter 6 slides fromRegesandStepp’sexcellent “Building Java Programs” textbook was used as the basis of these slides.The instructor was given permission by the publisher to use those slides in this course.Those slides were modified to work in C#.Java has two methods of interacting with files: token-based and line-based.C#’s implementation does not have this distinction (which avoids some problems at the cost of requiring more complicated code)
10
10

0

Embed

Share

Upload

Make amazing presentation for free
File I_O In C# - faculty.cascadia.edu