首页 > 编程语言 >C#中的文件操作

C#中的文件操作

时间:2022-11-05 14:35:32浏览次数:32  
标签:文件 fs string filePath C# sw File 操作

一、简介

简单记录一下在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;
}

 

标签:文件,fs,string,filePath,C#,sw,File,操作
From: https://www.cnblogs.com/just-like/p/16694327.html

相关文章

  • Destination folder must be accessible
    问题Ecplise拖入文件夹项目时提示错误:Destinationfoldermustbeaccessible解决导入的时候包不能直接拖入,要使用import导入,选择File->Import->Select->General->Exi......
  • $el,$nextTick,$set
    this.$elthis.$elDOM的根元素=>是一个完全唯一的$el直到组件挂载完成(mounted)之前都会是undefined。对于单一根元素的组件,$el将会指向该根元素。this.$nestT......
  • 访问springboot项目静态文件(图片)
    查看“1667626781298.jpg”图片  配置:application.properties的配置文件进行配置spring.mvc.static-path-pattern=/**spring.web.resources.static-locations=classp......
  • CSS & JS Effect – Textarea Autoresize
    前言这是一个很普遍的体验,而且实现起来也很简单哦 参考YouTube– HowtoAutoResizeTextareausingHTMLCSS&JavaScript 效果我故意加了border和pad......
  • mongodb 导出操作
    我的是备份数据库,链接到数据库服务器来备份的终端shell命令实现远程连接服务器:mongo-host10.202.***.**-port27017--authenticationDatabasexz**导出远程服......
  • Java 多线程写zip文件遇到的错误 write beyond end of stream!
    最近在写一个大量小文件直接压缩到一个zip的需求,由于zip中的entry每一个都是独立的,不需要追加写入,也就是一个entry文件,写一个内容,因此直接使用了多线程来处理,结果就翻......
  • 「题解」Codeforces 1612F Armor and Weapons
    首先可以不管套件,假定\(n<m\),那么答案不超过\(\mathcal{O}(\logn+\frac{m}{n})\),也就是先倍增把\(n\)造出来,然后一步步造\(m\).答案这么小,那么常见的套路就是把答案......
  • 问题解决:vscode运行python找不到文件
    问题描述:使用VSCode执行Python代码调用其他文件时报FileNotFound错误,终于发现是VSCode工作路径默认是当前文件所在工作区的根目录,而不是当前文件所在目录。发生条件:根......
  • springboot实现图片、文件接收
     1/**2*3*@paramfile4*@return5*/6@PostMapping(value="getCategoryByUserName")7publicStringupdateCo......
  • Java XSSF兼容高版本Excel文件
    Workbookworkbook=null;try{workbook=newHSSFWorkbook(file.getInputStream());//将获取的流转成Excel}ca......