一个项目中使用到的通用函数库(3) 文件IO操作!

本文介绍了一种文件IO操作的方法,包括创建或写入文件内容的功能,支持覆盖或追加模式,并提供了两种读取文件内容的方式:一种是通过字节数组转换为字符串,另一种则是逐行读取并拼接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#region 文件IO操作!
        
/// <summary>
        
/// 创建/写入文件内容
        
/// </summary>
        
/// <param name="FileName">文件名(默认当前目录/包含路径)</param>
        
/// <param name="FileContent">文件内容</param>
        
/// <param name="act">改写(false)/追加到文件尾部(true)</param>
        
/// <returns>返回bool</returns>
        public static bool IO_CreatTextFile(string FileName, string FileContent, bool act)
        {
            
try
            {
                StreamWriter writer1 
= new StreamWriter(FileName, act, Encoding.Default);
                writer1.Write(FileContent);
                writer1.Close();
            }
            
catch
            {
                
return false;
            }
            
return true;
        }
        
/// <summary>
        
/// 得到文件内容
        
/// </summary>
        
/// <param name="TextFilePath">文件路径</param>
        
/// <returns>文件内容字符串</returns>
        public static string IO_GetFileContent(string TextFilePath)
        {
            FileStream stream1 
= new FileStream(TextFilePath, FileMode.Open, FileAccess.Read);
            
byte[] buffer1 = new byte[(int)stream1.Length];
            stream1.Read(buffer1, 
0, buffer1.Length);
            stream1.Close();
            
return Encoding.Default.GetString(buffer1);
        }
        
/// <summary>
        
/// 读取文件内容
        
/// </summary>
        
/// <param name="TextFilePath">文件路径</param>
        
/// <returns></returns>
        public static string IO_GetFileContent1(string TextFilePath)
        {
            FileStream fs 
= new FileStream(TextFilePath, FileMode.Open);
            StreamReader sr 
= new StreamReader(fs);
            
string s = "";
            
while (sr.BaseStream.Position < sr.BaseStream.Length)
            {
                s 
+= sr.ReadLine();
            }
            
return s;
        }


        
#endregion
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值