using System.IO;
using System;
using System.IO;
namespace IO
{
class Program
{
public static void Main(string[] args)
{
//Specify a filestream containing the filename
FileStream fs = new FileStream("path.txt", FileMode.OpenOrCreate, FileAccess.Write);
//Create a stream to write to
StreamWriter sw = new StreamWriter(fs);
//Write
sw.WriteLine("Hello world!");
sw.WriteLine("What's hanging?");
//Close the stream
sw.Close();
//Close the file
fs.Close();
//Specify the the file to read from
fs = new FileStream("path.txt", FileMode.OpenOrCreate, FileAccess.Read);
//Create a stream to read to
StreamReader sr = new StreamReader(fs);
//Read the file
string theText = sr.ReadToEnd();
Console.WriteLine(theText);
sr.Close();
fs.Close();
Console.Read();
}
}
}
FileStream fs = new FileStream("path.txt", FileMode.OpenOrCreate, FileAccess.Write);
| FileMode Enumeration | Description |
|---|---|
| Create | FileMode.Create value creates a file and if the file already exists, it will be overwritten. |
| CreateNew | Creates a file and if the file already exists, an IOException is thrown. |
| Append | Opens the file and starts writing at the end of the file. If the file doesn't exist a file is created. Note that you can use FileMode.Append only with FileAccess.Write or an exception of type ArgumentException is thrown. |
| Open | Opens the file if it exists. If the file does not exist, an exception of type FileNotFoundException is thrown. |
| OpenOrCreate | Opens the file if it exists. If the file does not exist, the file will be created. |
| Truncate | Opens a file and truncates it to make it a size of zero bytes. |
| FileAccess Enumeration | Description |
|---|---|
| Read | Sets read access to the file. |
| Write | Sets write access to the file. |
| ReadWrite | Sets read/write access to the file. |
| FileShare Enumeration | Description |
|---|---|
| None | Obtains an exclusive access to the file until it's closed, which means that other streams can't read from or write to the file until this stream is closed. |
| Read | Other streams (in the current process or in another one) can obtain read access to the file. |
| Write | Other streams (in the current process or in another one) can obtain write access to the file |
| ReadWrite | Other streams can obtain ReadWrite access to the file |
There are no comments on this article.
If you have any question or just want to leave a message, just fill out the form below!
Your e-mail will not be visible in your post, it is for validation reasons only