using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace CSharpFileIoLab
{
internal class Program
{
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
string tempDir = Path.Combine(Path.GetTempPath(), "csharplab-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
try
{
// Case 1: FileStream WriteByte / Position=0 / ReadByte including -1 EOF
string datPath = Path.Combine(tempDir, "test.dat");
List<string> readTokens = new List<string>();
using (FileStream fs = new FileStream(datPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
for (int i = 1; i <= 20; i++)
{
fs.WriteByte((byte)i);
}
fs.Position = 0;
for (int i = 0; i <= 20; i++)
{
readTokens.Add(fs.ReadByte().ToString());
}
}
cases.Add(CaseJson(
"filestream_byte_rw_and_eof",
"Write bytes 1..20 with FileStream, reset Position=0, and read 21 times yielding 1..20 and -1 EOF",
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1",
string.Join(" ", readTokens.ToArray())
));
// Case 2: FileMode, FileAccess, FileShare behaviors
string modePath = Path.Combine(tempDir, "modes.txt");
bool openMissingThrew = false;
try
{
using (new FileStream(modePath, FileMode.Open, FileAccess.Read)) { }
}
catch (FileNotFoundException)
{
openMissingThrew = true;
}
File.WriteAllText(modePath, "abc", Encoding.UTF8);
bool createNewThrew = false;
try
{
using (new FileStream(modePath, FileMode.CreateNew, FileAccess.Write)) { }
}
catch (IOException)
{
createNewThrew = true;
}
using (FileStream fsTrunc = new FileStream(modePath, FileMode.Truncate, FileAccess.Write))
{
byte[] b = Encoding.ASCII.GetBytes("XY");
fsTrunc.Write(b, 0, b.Length);
}
using (FileStream fsApp = new FileStream(modePath, FileMode.Append, FileAccess.Write))
{
byte[] b = Encoding.ASCII.GetBytes("Z");
fsApp.Write(b, 0, b.Length);
}
string modeText = File.ReadAllText(modePath, Encoding.ASCII);
bool shareNoneBlocked = false;
using (FileStream lockFs = new FileStream(modePath, FileMode.Open, FileAccess.Read, FileShare.None))
{
try
{
using (new FileStream(modePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { }
}
catch (IOException)
{
shareNoneBlocked = true;
}
}
bool shareReadAllowed = false;
using (FileStream r1 = new FileStream(modePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (FileStream r2 = new FileStream(modePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
shareReadAllowed = (r1.Length == 3 && r2.Length == 3);
}
}
int accessCount = Enum.GetNames(typeof(FileAccess)).Length;
int modeCount = Enum.GetNames(typeof(FileMode)).Length;
int shareCount = Enum.GetNames(typeof(FileShare)).Length;
string actual2 = string.Format(
"openMiss={0};createNewExist={1};text={2};shareNone={3};shareRead={4};counts={5}/{6}/{7}",
openMissingThrew, createNewThrew, modeText, shareNoneBlocked, shareReadAllowed,
modeCount, accessCount, shareCount
);
cases.Add(CaseJson(
"filemode_access_share_enums",
"Verify FileMode (Open/CreateNew/Truncate/Append), FileAccess, and FileShare (None vs Read)",
"openMiss=True;createNewExist=True;text=XYZ;shareNone=True;shareRead=True;counts=6/3/6",
actual2
));
// Case 3: StreamWriter/StreamReader, BinaryWriter/BinaryReader, MemoryStream, BufferedStream, StringWriter/StringReader
string txtPath = Path.Combine(tempDir, "lines.txt");
using (StreamWriter sw = new StreamWriter(txtPath, false, Encoding.UTF8))
{
sw.WriteLine("hello-csharp");
}
string lineRead;
using (StreamReader sr = new StreamReader(txtPath, Encoding.UTF8))
{
lineRead = sr.ReadLine();
}
string binPath = Path.Combine(tempDir, "vals.bin");
using (FileStream bfs = new FileStream(binPath, FileMode.Create, FileAccess.Write))
using (BufferedStream buf = new BufferedStream(bfs))
using (BinaryWriter bw = new BinaryWriter(buf, Encoding.UTF8))
{
bw.Write(42);
bw.Write(3.5);
bw.Write("OK");
}
int bi;
double bd;
string bs;
using (BinaryReader br = new BinaryReader(File.Open(binPath, FileMode.Open, FileAccess.Read), Encoding.UTF8))
{
bi = br.ReadInt32();
bd = br.ReadDouble();
bs = br.ReadString();
}
string memResult;
using (MemoryStream ms = new MemoryStream())
{
byte[] data = Encoding.ASCII.GetBytes("MEM");
ms.Write(data, 0, data.Length);
ms.Position = 0;
memResult = Encoding.ASCII.GetString(ms.ToArray());
}
StringWriter strW = new StringWriter();
strW.Write("BUF");
string strR = new StringReader(strW.ToString()).ReadToEnd();
string actual3 = string.Format("txt={0};bin={1}/{2}/{3};mem={4};str={5}", lineRead, bi, bd, bs, memResult, strR);
cases.Add(CaseJson(
"text_and_binary_io_streams",
"Verify StreamReader/Writer, BinaryReader/Writer, BufferedStream, MemoryStream, and StringReader/Writer",
"txt=hello-csharp;bin=42/3.5/OK;mem=MEM;str=BUF",
actual3
));
// Case 4: Directory, DirectoryInfo, File, FileInfo, Path, DriveInfo
string subDir = Path.Combine(tempDir, "sub");
DirectoryInfo di = Directory.CreateDirectory(subDir);
string sampleFile = Path.Combine(subDir, "item.txt");
File.WriteAllText(sampleFile, "12345", Encoding.ASCII);
FileInfo fi = new FileInfo(sampleFile);
string ext = Path.GetExtension(sampleFile);
string root = Path.GetPathRoot(tempDir);
DriveInfo drv = new DriveInfo(root);
string actual4 = string.Format("dir={0};len={1};ext={2};driveReady={3}", di.Exists, fi.Length, ext, drv.IsReady);
cases.Add(CaseJson(
"filesystem_path_directory_file_info",
"Verify Directory/DirectoryInfo, File/FileInfo, Path, and DriveInfo operations inside temp workspace",
"dir=True;len=5;ext=.txt;driveReady=True",
actual4
));
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, true);
}
}
Console.WriteLine(string.Format(
"{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
Environment.Version.ToString(),
string.Join(",", cases.ToArray())
));
}
}
}
本例需在 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
入口文件:projects/csharp-file-io-lab/ExploreFileIo.cs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreFileIo.cs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a1321.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1334.zip