1 文本文件写入
1.1 File类写入
string filepath1 = @"F:\test.txt";
string[] strs = { "123", "456\n", "789" };
File.WriteAllLines(filepath1, strs);
File.WriteAllLines(filepath1, strs.ToList());
File.WriteAllLines(filepath1, strs, Encoding.Unicode);
File.AppendAllLines(filepath1, strs);
File.AppendAllLines(filepath1, strs.ToList());
File.AppendAllLines(filepath1, strs, Encoding.Unicode);
string filepath2 = @"F:\test1.txt";
File.WriteAllText(filepath2, strs[0]);
File.WriteAllText(filepath2, strs[0], Encoding.Unicode);
File.AppendAllText(filepath2, strs[0]);
File.AppendAllText(filepath2, strs[0], Encoding.Unicode);
1.2 StreamWriter 类写入
string path = @"F:\test.txt";
string[] strs = { "123", "456\n", "789" };
StreamWriter sw = new StreamWriter(path, false);
sw.Write("开始写入");
foreach (var str in strs)
{
sw.WriteLine(str);
}
sw.Write("写入完成");
sw.Close();
sw.Dispose();
2 文本文件读取
2.1 File 类读取
string path = @"F:\test.txt";
List<string> text1 = File.ReadLines(path).ToList();
string[] text2 = File.ReadAllLines(path);
string text3 = File.ReadAllText(path);
2.2 StreamReader 类读取
var sw = new StreamReader(path);
List<string> lstText = new List<string>();
string text;
while ((text = sw.ReadLine()) != null)
{
lstText.Add(text);
}
sw.Close();
sw.Dispose();
var sw = new StreamReader(path);
string text = sw.ReadToEnd();
sw.Close();
sw.Dispose();
3 字节流文件读写
3.1 FileStream
public static void Write(string path, byte[] bytes)
{
var fs = new FileStream(path, FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
}
public static void Read(string path, out byte[] bytes)
{
var fs = new FileStream(path, FileMode.Open);
bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
}
3.2 Md5
public static void WriteByMd5(string path, byte[] bytes)
{
var lst = bytes.ToList();
var md5 = MD5.Create();
var md5Buffer = md5.ComputeHash(bytes.ToArray());
lst.Add((byte)'\n');
lst.AddRange(md5Buffer);
var zip = new GZipStream(new FileStream(path, FileMode.Create), CompressionMode.Compress);
zip.Write(lst.ToArray(), 0, lst.Count);
zip.Close();
zip.Dispose();
}
public static void ReadByMd5(string path, out byte[] bytes)
{
try
{
var readBuffer = new List<byte>();
var zip = new GZipStream(new FileStream(path, FileMode.Open), CompressionMode.Decompress);
while (true)
{
try
{
var segment = new byte[102400];
var res = zip.Read(segment, 0, segment.Length);
if (res > 0)
readBuffer.AddRange(segment.Take(res));
else
break;
}
catch (Exception)
{
break;
}
}
zip.Close();
zip.Dispose();
var delimiterMd5 = readBuffer.Count - 16 - 1;
var dataBuffer = readBuffer.Take(delimiterMd5).ToArray();
var md52 = MD5.Create().ComputeHash(dataBuffer);
var md5Bufer = readBuffer.Skip(delimiterMd5 + 1).ToArray();
if (!md52.SequenceEqual(md5Bufer)) throw new Exception("文件已损坏");
bytes = dataBuffer.ToArray();
}
catch (Exception ex)
{
throw new Exception("文件已损坏", ex);
}
}