Материал из .Net Framework эксперт
Create FileStream from FileInfo with file mode, file access and file sharing
using System;
using System.IO;
public class MainClass
{
static void Main(string[] args)
{
FileInfo MyFiles = new FileInfo(@"c:\Testing.txt");
FileStream MyFileStream1 = MyFiles.Open(FileMode.Append, FileAccess.Read, FileShare.None);
int MyBytes = MyFileStream1.ReadByte();
MyFileStream1.Close();
}
}
Creates a file with read-write access that allows others to read
using System;
using System.IO;
public class MainClass
{
static void Main(string[] args)
{
FileStream MyFileStream1 = new FileStream(@"c:\Testing.txt", FileMode.Create);
int MyBytes = MyFileStream1.ReadByte();
MyFileStream1.Close();
}
}
FileStream is opened for FileAccess.ReadWrite (default) and FileShare.None (default)
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.rupression;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
public class MainClass
{
public static void Main()
{
using (FileStream fs1 = File.Open("c:\\test.txt", FileMode.Open)){
}
}
}
FileStream is opened for FileAccess.ReadWrite FileShare.Read and has had its entire contents truncated (due to FileMode.Truncate)
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.rupression;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
public class MainClass
{
public static void Main()
{
using (FileStream fs3 =File.Open("c:\\test.txt", FileMode.Truncate, FileAccess.ReadWrite, FileShare.Read))
{
}
}
}
FileStream is opened for FileAccess.Write FileShare.None (default) and is positioned at the end (because of FileMode.Append)
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.rupression;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
public class MainClass
{
public static void Main()
{
using (FileStream fs2 = File.Open("c:\\test.txt", FileMode.Append, FileAccess.Write))
{
}
}
}
Use FileStream with StreamWriter to provide a greater degree of control in how you open the file
using System;
using System.IO;
public class MainClass
{
static void Main(string[] args)
{
FileStream MyFileStream = new FileStream(@"c:\Testing.txt", FileMode.CreateNew, FileAccess.Write, FileShare.None);
StreamWriter MyStreamWriter = new StreamWriter(MyFileStream);
MyStreamWriter.Write("a string");
MyFileStream.Close();
MyStreamWriter.Close();
}
}