---
lang: ja-jp
breaks: true
---
# C# 各種ファイル操作 2022-04-02
## 簡単にテキストファイルを全て読み込む
```csharp=
FileInfo file = new(source.Path);
if (file.Exists == false)
{
throw new Exception($"source not found.[{source.Path}]");
}
string strSource;
using (StreamReader stream = file.OpenText())
{
strSource = await stream.ReadToEndAsync();
stream.Close()
}
```
:::warning
`.NET Framework`と`.NET Core`で対応する文字コードが異なるので、クリティカルな処理には使えない。
:::
## 簡単にテキストファイルを書き込む
```csharp=
File.WriteAllText(fileinfo.FullName, text, Encoding.UTF8);
```
:::info
`.NET Framework`でBOM付で書き込まれる。
:::
## UTF-8 BOM付で書き込む
```csharp=
FileInfo file = new(source.Path);
using (StreamWriter stream = new StreamWriter(file.FullName, false, new UTF8Encoding(true)))
{
stream.BaseStream.SetLength(0);
await stream.WriteAsync(strCompleted);
stream.Close();
}
```
## ファイルをバイナリのままバイト配列で全て読み込む
```csharp=
byte[] bytBuf = null;
using (FileStream fileStream = new(
filepath,
FileMode.Open,
FileAccess.Read
)
)
{
long fileSize = fileStream.Length; // ファイルのサイズ
bytBuf = new byte[fileSize]; // データ格納用配列
int readSize; // Readメソッドで読み込んだバイト数
long remain = fileSize; // 読み込むべき残りのバイト数
int bufPos = 0; // データ格納用配列内の追加位置
while (remain > 0)
{
// 1024Bytesずつ読み込む
readSize = fileStream.Read(bytBuf, bufPos, (int)Math.Min(1024, remain));
bufPos += readSize;
remain -= readSize;
}
fileStream.Close();
}
```
:::warning
これは、どこかネットからパクってきたソース。
:::
### 簡単なバージョン
```csharp=
static byte[] GetBytes(FileInfo file)
{
byte[] bytes = File.ReadAllBytes(file.FullName);
return bytes;
}
```
## バイト配列をバイナリのまま書き込む
```csharp=
byte[] bytBuf = new byte[fileSize]; // データ格納用配列
・・・
using (
FileStream stream = new FileStream(
fli_mst_manifest.FullName,
FileMode.CreateNew,
FileAccess.Write
)
)
{
ulong offset = 0uL;
while (offset < (ulong)bytBuf.Length)
{
// 1024Bytesずつ書き込む
int length = (int)Math.Min((ulong)bytBuf.Length - offset, 1024uL);
stream.Write(bytBuf, (int)offset, length);
offset += (ulong)length;
}
}
```
## テキストファイルを文字コードを指定して全て読み込む
```csharp=
Encoding enc = System.Text.Encoding.GetEncoding(932);
string strReadAll;
using (StreamReader stream = new(strPath, enc))
{
strReadAll = stream.ReadToEnd();
stream.Close();
}
```
## バイト列を文字列として読み込む
```csharp=
Encoding enc = System.Text.Encoding.GetEncoding(932);
byte[] bytsData = ...;
string strReadAll;
using (MemoryStream memory = new(bytsData))
{
using (StreamReader stream = new(memory, enc))
{
string strReadAll = stream.ReadToEnd();
stream.Close();
}
}
```
###### tags: `C#` `ファイル操作` `テキスト` `バイナリ` `バイト列` `byte[]` `UTF-8` `BOM`