Open a File in C#

Introduction

 
The Open method opens a FileStream on the specified file.
 

File.Open Method

  1. FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Write, FileShare.None);  

Open a File in C#

 
This method used Opens a FileStream on the specified path.
 

FileStream Class

 
The FileStream Class Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations.
 
Syntax
  1. [System.Runtime.InteropServices.ComVisible(true)]  
  2. public class FileStream: System.IO.Stream   
Example
 
The following example demonstrates some of the FileStream constructors.
  1. using System;  
  2. using System.IO;  
  3. using System. Text;  
  4.   
  5. class Test  
  6. {  
  7.   
  8.     public static void Main()  
  9.     {  
  10.         string path = @"c:\temp\MyTest.txt";  
  11.   
  12.         // Delete the file if it exists.  
  13.         if (File.Exists(path))  
  14.         {  
  15.             File.Delete(path);  
  16.         }  
  17.   
  18.         //Create the file.  
  19.         using (FileStream fs = File.Create(path))  
  20.         {  
  21.             AddText(fs, "This is some text");  
  22.             AddText(fs, "This is some more text,");  
  23.             AddText(fs, "\r\nand this is on a new line");  
  24.             AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");  
  25.   
  26.             for (int i=1;i < 120;i++)  
  27.             {  
  28.                 AddText(fs, Convert.ToChar(i).ToString());  
  29.   
  30.             }  
  31.         }  
  32.   
  33.         //Open the stream and read it back.  
  34.         using (FileStream fs = File.OpenRead(path))  
  35.         {  
  36.             byte[] b = new byte[1024];  
  37.             UTF8Encoding temp = new UTF8Encoding(true);  
  38.             while (fs.Read(b,0,b.Length) > 0)  
  39.             {  
  40.                 Console.WriteLine(temp.GetString(b));  
  41.             }  
  42.         }  
  43.     }  
  44.   
  45.     private static void AddText(FileStream fs, string value)  
  46.     {  
  47.         byte[] info = new UTF8Encoding(true).GetBytes(value);  
  48.         fs.Write(info, 0, info.Length);  
  49.     }  
  50. }  
The following example shows how to write to a file asynchronously. This code runs in a WPF app that has a TextBlock named UserInput and a button hooked up to a Click event handler that is named Button_Click. The file path needs to be changed to a file that exists on the computer in this method.
  1. using System;  
  2. using System.Text;  
  3. using System.Threading.Tasks;  
  4. using System.Windows;  
  5. using System.Windows.Controls;  
  6. using System.IO;  
  7.   
  8. namespace WpfApplication1  
  9. {  
  10.     public partial class MainWindow : Window  
  11.     {  
  12.         public MainWindow()  
  13.         {  
  14.             InitializeComponent();  
  15.         }  
  16.   
  17.         private async void Button_Click(object sender, RoutedEventArgs e)  
  18.         {  
  19.             UnicodeEncoding uniencoding = new UnicodeEncoding();  
  20.             string filename = @"c:\Users\exampleuser\Documents\userinputlog.txt";  
  21.              
  22.             byte[] result = uniencoding.GetBytes(UserInput.Text);  
  23.               
  24.             using (FileStream SourceStream = File.Open(filename, FileMode.OpenOrCreate))  
  25.             {  
  26.                 SourceStream.Seek(0, SeekOrigin.End);  
  27.                 await SourceStream.WriteAsync(result, 0, result.Length);  
  28.             }  
  29.         }  
  30.     }  
  31. }  
The FileStream has used a class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the Read, Write, CopyTo, and Flush methods to perform synchronous operations, or the ReadAsync, WriteAsync, CopyToAsync, and FlushAsync methods to perform asynchronous operations.
 
The File Stream uses the asynchronous method to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. FileStream buffers input and output for better performance.
 
Note
 
This method uses the Disk files which always support random access. At the time of construction, the CanSeek property value is set to true or false depending on the underlying file type. If the underlying file type is FILE_TYPE_DISK, as defined in win base.h, the CanSeek property value is true. Otherwise, the CanSeek property value is false.
 
This type of method Implement the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.
 
The IsAsync property detects whether the filehandle was opened asynchronously. You specify this value when you create an instance of the FileStream class using a constructor that has an isAsync, useAsync, or options parameter. When the property is true, the stream utilizes overlapped I/O to perform file operations asynchronously.
 
However, the IsAsync property does not have to be true to call the ReadAsync, WriteAsync, or CopyToAsync method. When the IsAsync property is false and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously.
 
The Seek method supports random access to files. Seek allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the SeekOrigin enumeration in this method.
 
If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.
 
For directory operations and other file operations, see the File, Directory, and Path classes. The File class is a utility class that has static methods primarily for the creation of FileStream objects based on file paths. The MemoryStream class creates a stream from a byte array and is similar to the FileStream class.
 
For a list of common file and directory operations, see Common I/O Tasks.
 

Detection of Stream Position Changes

 
When a FileStream object does not have an exclusive hold on its handle, another thread could access the filehandle concurrently and change the position of the operating system's file pointer that is associated with the filehandle. In this case, the cached position in the FileStream object and the cached data in the buffer could be compromised. The FileStream object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the FileStream object.
 
If an unexpected change in the handle position is detected in a call to the Read method, the .NET Framework discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream.
 
If an unexpected change in the handle position is detected in a call to the write method, the contents of the buffer are discarded and an IOException exception is thrown.
A FileStream object will not have an exclusive hold on its handle when either the SafeFileHandle property is accessed to expose the handle or the FileStream object is given the SafeFileHandle property in its constructor.
 

File Mode

 
The FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
 
Example
 
The following example creates a temporary file and writes some text to it. The example then opens the file, using T:System.IO.FileMode.Open; that is, if the file did not already exist, it would not be created.
  1. using System;  
  2. using System.IO;  
  3. using System. Text;  
  4.   
  5. class Test   
  6. {  
  7.     public static void Main()   
  8.     {  
  9.         // Create a temporary file, and put some data into it.  
  10.         string path = Path.GetTempFileName();  
  11.         using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None))   
  12.         {  
  13.             Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");  
  14.             // Add some information to the file.  
  15.             fs.Write(info, 0, info.Length);  
  16.         }  
  17.           
  18.   
  19.         // Open the stream and read it back.  
  20.         using (FileStream fs = File.Open(path, FileMode.Open))   
  21.         {  
  22.             byte[] b = new byte[1024];  
  23.             UTF8Encoding temp = new UTF8Encoding(true);  
  24.   
  25.             while (fs.Read(b,0,b.Length) > 0)   
  26.             {  
  27.                 Console.WriteLine(temp.GetString(b));  
  28.             }  
  29.         }  
  30.     }  
  31. }   
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
 
For a list of common I/O tasks, see Common I/O Tasks.
 

Security

 
FileIOPermission for reading from and writing to the specified file. Associated enumerations: Read, Write. 
  1. File Open(String, FileMode, FileAccess)    
File Opens a FileStream on the specified path, with the specified mode and access with no sharing.
 
Syntax
  1. public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access);    
The following example opens a file with read-only access.
  1. using System;  
  2. using System.IO;  
  3. using System. Text;  
  4.   
  5. class Test   
  6. {  
  7.     public static void Main()   
  8.     {  
  9.         // This sample assumes that you have a folder named "c:\temp" on your computer.  
  10.         string filePath = @"c:\temp\MyTest.txt";  
  11.   
  12.         // Delete the file if it exists.  
  13.         if (File.Exists(filePath))   
  14.         {  
  15.             File.Delete(filePath);  
  16.         }  
  17.           
  18.         // Create the file.  
  19.         using (FileStream fs = File.Create(filePath))   
  20.         {  
  21.             Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");  
  22.             // Add some information to the file.  
  23.             fs.Write(info, 0, info.Length);  
  24.         }  
  25.   
  26.         // Open the stream and read it back.  
  27.         using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))   
  28.         {  
  29.             byte[] b = new byte[1024];  
  30.             UTF8Encoding temp = new UTF8Encoding(true);  
  31.   
  32.             while (fs.Read(b,0,b.Length) > 0)   
  33.             {  
  34.                 Console.WriteLine(temp.GetString(b));  
  35.             }  
  36.   
  37.             try   
  38.             {  
  39.                 // Try to write to the file.  
  40.                 fs.Write(b,0,b.Length);  
  41.             }   
  42.             catch (Exception e)   
  43.             {  
  44.                 Console.WriteLine("Writing was disallowed, as expected: {0}", e.ToString());  
  45.             }  
  46.         }  
  47.     }  
  48. }  
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.
 

GetCurrentDirectory Method

 
This Method Gets the current working directory of the application.
 
Syntax
  1. public static string GetCurrentDirectory ();   
Example 
 
The following example demonstrates how to use the GetCurrentDirectory method.
  1. using System;  
  2. using System.IO;  
  3.   
  4. class Test   
  5. {  
  6.     public static void Main()   
  7.     {  
  8.         try   
  9.         {  
  10.             // Get the current directory.  
  11.             string path = Directory.GetCurrentDirectory();  
  12.             string target = @"c:\temp";  
  13.             Console.WriteLine("The current directory is {0}", path);  
  14.             if (!Directory.Exists(target))   
  15.             {  
  16.                 Directory.CreateDirectory(target);  
  17.             }  
  18.   
  19.             // Change the current directory.  
  20.             Environment.CurrentDirectory = (target);  
  21.             if (path.Equals(Directory.GetCurrentDirectory()))   
  22.             {  
  23.                 Console.WriteLine("You are in the temp directory.");  
  24.             }   
  25.             else   
  26.             {  
  27.                 Console.WriteLine("You are not in the temp directory.");  
  28.             }  
  29.         }   
  30.         catch (Exception e)   
  31.         {  
  32.             Console.WriteLine("The process failed: {0}", e.ToString());  
  33.         }  
  34.     }  
  35. }  
The current directory is distinct from the original directory, which is the one from which the process was started.
 

Summary

 
In this article, we learned about how to open a file in C# and use of File.open() method and File.OpenRead() methods in C#.


Similar Articles