C#中的文件操作

一、简介

简单记录一下在c#中文件的操作,文件目录的创建,以及文件的创建和读写

二、文件操作

2.1 获取程序当前目录

string path1 = AppDomain.CurrentDomain.BaseDirectory;//D:\\work\\app1\\bin\\Debug\\
string path2 = Directory.GetCurrentDirectory();//D:\\work\\app1\\bin\\Debug

这两个都可以获取当前程序的目录,根据获取到的路径可以看到path1比path2多了一个\,当需要获取当前程序目录时,使用这两个中的任何一个都可以

2.2 判断及创建文件

if (!Directory.Exists(path2))//检测文件目录是否存在
{
    Directory.CreateDirectory(path2);//创建该文件目录  
}
string filePath = Path.Combine(path2, "log.txt");
if (!File.Exists(filePath))//检测文件是否存在
{
    File.Create(filePath);//创建文件  当该文件存在时,会被新创建的文件覆盖掉
}

DirectoryInfo directory = new DirectoryInfo(filePath);//即使文件不存在,也不会报错,新建的对象相当于对该文件的一种描述,可以根据属性看到文件的创建时间,修改时间以及该文件是否存在

2.3 文件夹及文件操作

Directory.Move(sourceDirName, destDirName);//将文件夹及其文件移动到新位置  
Directory.Delete(path);//删除指定路径空目录

2.4 文件内容读取和写入

第一种写入方式 使用 StreamWriter 

if (!Directory.Exists(sFilePath))//验证路径是否存在
{
    Directory.CreateDirectory(sFilePath);//不存在则创建
}
FileStream fs;
StreamWriter sw;
if (File.Exists(sFileName))//验证文件是否存在,有则追加,无则创建
{
     fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);//文件存在则追加
}
else
{
    fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);//不存在则创建
}
sw = new StreamWriter(fs);
sw.WriteLine(logstr);
sw.Flush();//清空写入器缓冲区,并将内容写入到文件中
sw.Close();//关闭连接
fs.Close();
fs.Dispose();//可使用using简化

第二种只使用 FileStream 写入

using (FileStream fs= File.Create(fileName))//打开文件流 (创建文件并写入)
{
    string str="1100";
    byte[] bytes = Encoding.Default.GetBytes(str);
    fs.Write(bytes, 0, bytes.Length);
    fs.Flush();
}

第三种,使用File.AppendText()

using (StreamWriter sw = File.AppendText(filePath))//流写入器(创建/打开文件并写入)
{
    string str= "4152311";
    byte[] bytes = Encoding.Default.GetBytes(str);
    sw.BaseStream.Write(bytes, 0, bytes.Length);
    sw.Flush();
}

using (StreamWriter sw = File.AppendText(fileName))
{
    string msg = "135534355";
    sw.WriteLine(msg);
    sw.Flush();
}

2.5 读取文件内容

 第一种 一次性全部加载入内存中

string text = File.ReadAllText(fileName);//获取文本
byte[] txtByteArray= File.ReadAllBytes(fileName);
string text1= Encoding.UTF8.GetString(txtByteArray);//转换为文本

第二种 从流中分批读取字节块加入到内存中

using (FileStream stream = File.OpenRead(fileName))
{
    int length = 6;
    int result = -1;
    while (result != 0)
    {
        byte[] bytes = new byte[length];
        result = stream.Read(bytes, 0, length);
    }
}

第三种 读取二进制文件

public static byte[] ReadBinFile(string filePath)
{
    byte[] filedata = null;
    FileInfo mmidFile = new FileInfo(filePath);
    if (!mmidFile.Exists)    
        return filedata;
    FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    BinaryReader myReader = new BinaryReader(myFile);
    filedata = myReader.ReadBytes((int)myFile.Length);
    myReader.Dispose();
    myFile.Dispose();
    return filedata;
}

 

posted @ 2022-11-05 14:16  just--like  阅读(577)  评论(0编辑  收藏  举报