首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#中读写文件

在C#中读写文件可以使用System.IO命名空间中的类和方法。以下是一些常用的方法:

  1. 读取文件:
代码语言:csharp
复制
using System.IO;

string path = "file.txt";
using (StreamReader sr = new StreamReader(path))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
  1. 写入文件:
代码语言:csharp
复制
using System.IO;

string path = "file.txt";
using (StreamWriter sw = new StreamWriter(path))
{
    sw.WriteLine("Hello, World!");
}
  1. 读取二进制文件:
代码语言:csharp
复制
using System.IO;

string path = "file.bin";
using (BinaryReader br = new BinaryReader(File.Open(path, FileMode.Open)))
{
    int length = (int)br.BaseStream.Length;
    byte[] data = br.ReadBytes(length);
}
  1. 写入二进制文件:
代码语言:csharp
复制
using System.IO;

string path = "file.bin";
using (BinaryWriter bw = new BinaryWriter(File.Open(path, FileMode.Create)))
{
    byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 };
    bw.Write(data);
}

推荐的腾讯云相关产品和产品介绍链接地址:

  1. 腾讯云COS:https://cloud.tencent.com/product/cos
  2. 腾讯云CAM:https://cloud.tencent.com/product/cam
  3. 腾讯云CLB:https://cloud.tencent.com/product/clb
  4. 腾讯云CDB:https://cloud.tencent.com/product/cdb
  5. 腾讯云CVM:https://cloud.tencent.com/product/cvm
  6. 腾讯云CNS:https://cloud.tencent.com/product/cns
  7. 腾讯云CLS:https://cloud.tencent.com/product/cls
  8. 腾讯云API Gateway:https://cloud.tencent.com/product/tmt
  9. 腾讯云TKE:https://cloud.tencent.com/product/tke
  10. 腾讯云EKS:https://cloud.tencent.com/product/eks

以上是我的回答,如果您有任何问题,请随时问我。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券