Home
Map
File.Open ExampleUse the File.Open method with the FileStream and BinaryReader types.
C#
This page was last reviewed on Feb 15, 2024.
File.Open. How can you use the File.Open method in a C# program? Found in the System.IO namespace, File.Open returns a FileStream that you can use.
Method arguments. The arguments you pass to the File.Open method determine its action. It is often used within a using-statement.
File
Example. Here we use File.Open as part of the using-resource-acquisition pattern. This ensures proper recovery of system resources.
Argument 1 The first argument is the path (including the name) of the file we are acting upon.
Argument 2 With FileMode.Create, we create a new file (or create it again if it already exists). With FileMode.Open, we open an existing file.
using
using System; using System.IO; class Program { static void Main() { using (FileStream stream = File.Open("C:\\bin", FileMode.Create)) using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write(303); writer.Write(720); } using (FileStream stream = File.Open("C:\\bin", FileMode.Open)) using (BinaryReader reader = new BinaryReader(stream)) { int a = reader.ReadInt32(); int b = reader.ReadInt32(); Console.WriteLine(a); Console.WriteLine(b); } } }
303 720
FileMode. To use FileMode, type FileMode and press the period key, and then read the descriptions for each constant in Visual Studio. The constants are fairly self-descriptive.
FileMode.Append FileMode.Create FileMode.CreateNew FileMode.Open FileMode.OpenOrCreate FileMode.Truncate
Notes, types. BinaryWriter and BinaryReader are a practical use of FileStream. These constructors receive Stream references. This means they can be used with File.Open.
Info Because File.Open returns a FileStream, and FileStream is derived from Stream, we can use FileStream in the constructors.
Stream
BinaryWriter
BinaryReader
Round-tripping. We can see in this program that the numbers 303 and 720 are written to the "C:\bin" file. Then, they are read back into integers from that same file.
Alternatives. You can instead call File.OpenRead, File.OpenText and File.OpenWrite. Conceptually, these methods are the same as using File.Open with certain FileMode arguments.
Summary. We used the File.Open method and described FileMode. With the using statement we can use File.Open as part of a powerful file-handling construction.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 15, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.