Класс FileStream
FileStream наследует
Stream
и открывает файл по пути. В конструктор
передают FileMode и FileAccess;
режим Create обрезает существующий
файл. Удобная обёртка -
File.Open.
В примерах путь берут через
GetTempFileName
и удаляют File.Delete. Есть *Async
у чтения и записи.
Синтаксис
using System.IO;
using FileStream stream = new FileStream(
path, FileMode.Create, FileAccess.Write);
Пример
Давайте запишем "abcde"
во временный файл и прочитаем:
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string path = Path.GetTempFileName();
try
{
byte[] data = Encoding.UTF8.GetBytes("abcde");
using (FileStream write = new FileStream(
path, FileMode.Create, FileAccess.Write))
{
write.Write(data, 0, data.Length);
}
using (FileStream read = new FileStream(
path, FileMode.Open, FileAccess.Read))
{
byte[] buf = new byte[5];
read.Read(buf, 0, 5);
string res = Encoding.UTF8.GetString(buf);
Console.WriteLine(res);
}
}
finally
{
File.Delete(path);
}
}
}
Результат выполнения кода:
"abcde"
Пример
Давайте покажем, что FileMode.Create
заменяет старое содержимое:
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
string path = Path.GetTempFileName();
try
{
using (FileStream first = new FileStream(
path, FileMode.Create, FileAccess.Write))
{
byte[] old = Encoding.UTF8.GetBytes("12345");
first.Write(old, 0, old.Length);
}
using (FileStream second = new FileStream(
path, FileMode.Create, FileAccess.Write))
{
byte[] neu = Encoding.UTF8.GetBytes("abcde");
second.Write(neu, 0, neu.Length);
}
using (FileStream read = new FileStream(
path, FileMode.Open, FileAccess.Read))
{
byte[] buf = new byte[5];
read.Read(buf, 0, 5);
string res = Encoding.UTF8.GetString(buf);
Console.WriteLine(res);
}
}
finally
{
File.Delete(path);
}
}
}
Результат выполнения кода:
"abcde"
Пример
Давайте запишем через ReadOnlySpan
байтов в .NET 9:
using System;
using System.IO;
class Program
{
static void Main()
{
string path = Path.GetTempFileName();
try
{
ReadOnlySpan<byte> data = stackalloc byte[] { 97, 98, 99, 100, 101 };
using (FileStream stream = new FileStream(
path, FileMode.Create, FileAccess.Write))
{
stream.Write(data);
}
using (FileStream stream = new FileStream(
path, FileMode.Open, FileAccess.Read))
{
byte[] buf = new byte[5];
stream.Read(buf, 0, 5);
string res = System.Text.Encoding.UTF8.GetString(buf);
Console.WriteLine(res);
}
}
finally
{
File.Delete(path);
}
}
}
Результат выполнения кода:
"abcde"
Смотрите также
-
Stream,
базовый контракт потока -
Write,
запись байтов -
File.Open,
открытьFileStream -
MemoryStream,
поток в памяти