C#文件的读、写

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

/// 
/// 通过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();
}

/// 
/// 通过Md5和zip读取字节流文件
/// 
/// 文件路径
/// 返回读取到的字节数组
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();

        //校验md5
        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);
    }
}

你可能感兴趣的:(C#文件(流),c#)