Difference between revisions of "You can read a file but can't write a file to save it"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Explanation)
(Explanation)
Line 38: Line 38:
 
==Explanation==
 
==Explanation==
  
I have swapped the StreamReader from the original code to StreamWriter. Inside the second for loop Write (Line 12) is used to add the value onto the end of the current line. Outside of the second for loop but inside the first for loop the WriteLine will write nothing onto the current line, but then move down to the next line.
+
I have swapped the StreamReader from the original code to StreamWriter. Inside the second for loop Write (Line 13) is used to add the value onto the end of the current line. Outside of the second for loop but inside the first for loop the WriteLine (Line 15) will write nothing onto the current line, but then move down to the next line.
  
 
You could extend this by check to see if the filename entered exists to avoid writing over that file.
 
You could extend this by check to see if the filename entered exists to avoid writing over that file.

Revision as of 10:26, 10 March 2017

I started by copying the ReadFile code, if the code reads the data it should tell you the order you need to write.

Examining the code each row of the field is written as a single line in the file, this is confirmed by the data file:

Data file.gif

Interestingly the vertical line character and the number at the end of the row are never read from the file. So my saved file looks like:

Saved data file.gif

The Code

 1  static void SaveFile(char[,] Field)
 2         {
 3             string FileName = "";
 4             Console.Write("Enter file name: ");
 5             FileName = Console.ReadLine();
 6             try
 7             {
 8                 StreamWriter CurrentFile = new StreamWriter(FileName);
 9                 for (int Row = 0; Row < FIELDLENGTH; Row++)
10                 {
11                     for (int Column = 0; Column < FIELDWIDTH; Column++)
12                     {
13                         CurrentFile.Write(Field[Row, Column]);
14                     }
15                     CurrentFile.WriteLine();
16                 }
17                 CurrentFile.Close();
18             }
19             catch (Exception)
20             {
21                 Console.WriteLine("Save field failed!!");
22             }
23         }

Explanation

I have swapped the StreamReader from the original code to StreamWriter. Inside the second for loop Write (Line 13) is used to add the value onto the end of the current line. Outside of the second for loop but inside the first for loop the WriteLine (Line 15) will write nothing onto the current line, but then move down to the next line.

You could extend this by check to see if the filename entered exists to avoid writing over that file.