Ejemplo n.º 1
0
 /// <summary>
 /// Open an existing text file for reading
 /// </summary>
 /// <param name="filePath">
 /// The file path and file name of the text file to be opened
 /// </param>
 public virtual void OpenForRead(string filePath)
 {
     // Check to see if the file is already open. Throw an exception if it is.
     if (State == FileState.OPEN)
     {
         throw new FileOpenException("File already open")
               {
                   FilePath = DirectoryPath,
                   FileName = FileName
               };
     }
     // Obtain the absolute file path. Throw an exception if the path is invalid.
     ParseFilePath(filePath);
     // Throw an exception if the file doesn't exist.
     FileOps.FileMustExist(FilePath);
     State = FileState.OPEN;
     Mode  = FileMode.READ;
     // Read the contents of the file into the _fileData collection
     try
     {
         using (StreamReader sr = new StreamReader(FilePath))
         {
             while (sr.Peek() >= 0)            // Check to see if we've reached the end of the file
             {
                 _fileData.Add(sr.ReadLine()); // Read the next line from the file
             }
             if (Count > 0)
             {
                 Position = 0;            // Set the position index to the first line
             }
             else
             {
                 Position = -1;  // Set position index to a negative number if the file is empty
             }
         }
     }
     catch (Exception e)
     {
         string msg = $"Error reading line {Count + 1} from file";
         throw new FileIOException(msg, e)
               {
                   FilePath = DirectoryPath,
                   FileName = FileName
               };
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Open an existing text file for writing
 /// </summary>
 /// <param name="filePath">
 /// The file path and file name of the text file to be opened
 /// </param>
 public virtual void OpenForWrite(string filePath)
 {
     // Check to see if the file is already open. Throw an exception if it is.
     if (State == FileState.OPEN)
     {
         throw new FileOpenException("File already open")
               {
                   FilePath = DirectoryPath,
                   FileName = FileName
               };
     }
     // Obtain the absolute file path.
     ParseFilePath(filePath);
     // Throw an exception if the file doesn't exist.
     FileOps.FileMustExist(FilePath);
     // Finish opening the text file for writing
     State    = FileState.OPEN;
     Mode     = FileMode.WRITE;
     Position = 0;
 }