【美高梅开户网址】读取txt文书档案和写入文书档案的不二诀窍,文件读写操作

StreamReader sr = ``new StreamReader(path); ``//path是要读取的文件的完整路径

美高梅开户网址 1美高梅开户网址 2Code
using System;
using System.IO;
/*从文本文件中读也许写文本时,首先需创造八个与公事有关的StreamReader恐怕StreamWriter对象
 每2个StreamReader或StreamWriter对象都与一种字符编码格局有关。私下认可UTF八Encoding
*/
class FileOperate
{
    public static  string content=””;
    public static  StreamReader sr=null;
    public static StreamWriter sw=null;
    //读取文本时,有很多主意可以创立与公事名相关的Streamreader对象   
    /// <summary>
    ///方法一: 从文件名一贯开立
    /// </summary>
    public void ReadFromFileName()
    {
        
        try
        {
            sr=new StreamReader (“TestFile.txt”);
            string txt=””;
            while((txt=sr.ReadLine())!=null)
            {
                content+=txt;
            }
            Console.WriteLine (“—-ReadFromFileName——“);
            Console.WriteLine (content);
        }
        catch(Exception ex)
        {
            Console.WriteLine (ex.Message);
        }
        finally
        {
            sr.Close ();
        }
        
    }
    /// <summary>
    ///方法2: 使用File类大概FileInfo类的OpenText方法创立
    /// </summary>
    public void ReadUseFileOrFileInfo()
    {
        
        try
        {
         FileInfo fi=new FileInfo (“TestFile.txt”);
         sr=fi.OpenText();
         content=””;
         while(!sr.EndOfStream)
         {
            content+=sr.ReadLine();
         }
            Console.WriteLine (“—-ReadUseFileOrFileInfo——“);
            Console.WriteLine (content);        
        }
        catch(Exception ex)
【美高梅开户网址】读取txt文书档案和写入文书档案的不二诀窍,文件读写操作。        {
            Console.WriteLine (ex.Message);
        }
        finally
        {
            sr.Close ();
        }
        
    }
    
    /// <summary>
    /// 方法叁:通过FileStream对象创制
    /// </summary>
    public void ReadThroughFileStream()
    {
        //打开文件 只读
        FileStream fs1=new FileStream(“TestFile.txt”,FileMode.Open,FileAccess.Read );
        //打开文件 读写
        //FileStream fs2=File.Open (“TestFile.txt”,FileMode.Open ,FileAccess.ReadWrite);
        //打开文件 读写
        //FileStream fs3=File.Create(“TestFile.txt”);
        //打开文件 只读
        //FileStream fs4=File.OpenRead(“TestFile.txt”);
            
        try
        {
         sr=new StreamReader (fs1);
         content=””;
         while(!sr.EndOfStream)
         {
            content+=sr.ReadLine();
         }
         Console.WriteLine (“—-ReadThroughFileStream——“);
         Console.WriteLine (content);    
        }
        catch(Exception ex)
        {
          Console.WriteLine (ex.Message);
        }
        finally
        {
            fs1.Close ();
            sr.Close ();
        }
    }
    //写入文件 三种情势
    /// <summary>
    /// 方法1:通过文件名创制
    /// </summary>
    public void WriteFromFileName()
    {
        try
        {
            sw=new StreamWriter(“TestFile.txt”);
            Console.WriteLine (“Input Write File’s Content:”);
            string lines=Console.ReadLine ();
            sw.WriteLine(lines);
        }
        catch(Exception ex)
        {
            Console.WriteLine (ex.Message );
        }
        finally
        {
            sw.Close ();
        }
    }
    /// <summary>
    /// 文件写入措施贰:使用File类可能FileInfo类的CreateText或AppendText方法来成立
    /// AppendText方法:对于文本内容开始展览充实 CreateText方法:会删除已经存在的公文
    /// 缺点:只可以创制帮忙UTF8Encoding的StreamWriter对象
    /// </summary>
    public void WriteUseFileOrFileInfo()
    {
      //File类的CreateText方法
      StreamWriter sw1=File.CreateText(“TestFile.txt”);
      sw1.WriteLine(“File类的CreateText方法”);
      sw1.Close ();
     //FileInfo CreateText 
      FileInfo fi1=new FileInfo (“TestFile.txt”);
      StreamWriter sw2=fi1.CreateText();
      sw2.WriteLine(“FileInfo CreateText “);
      sw2.Close ();
      //File类的AppendText方法
      StreamWriter sw3=File.AppendText(“TestFile.txt”);
      sw3.WriteLine(“File类的AppendText方法”);
      sw3.Close ();
      //FileInfo 的AppendText
      FileInfo fi2=new FileInfo (“TestFile.txt”);
      StreamWriter sw4=fi2.AppendText();
      sw4.WriteLine(“FileInfo 的AppendText”);
      sw4.Close ();
    }
    /// <summary>
    /// 通过FileStream对象来成立
    /// </summary>
    public void WriteThroughFileStream()
    {
    
        //打开文件 只写
        FileStream fs1=new FileStream(“TestFile.txt”,FileMode.Open,FileAccess.Write);
        StreamWriter sw1=new StreamWriter(fs1);
        sw一.WriteLine(“通过FileStream对象来创立”);      
        sw1.Close ();
        fs1.Close ();
        //打开文件 读写
        FileStream fs2=File.Open (“TestFile.txt”,FileMode.Open ,FileAccess.ReadWrite);
        StreamWriter sw2=new StreamWriter(fs2);
        sw2.WriteLine(“通过File.Open创建FileStream对象”);       
        sw2.Close ();
        fs2.Close ();
        //打开文件 读写
        FileStream fs3=File.Create(“TestFile.txt”);
        StreamWriter sw3=new StreamWriter(fs3);
        sw3.WriteLine(“通过File.Create创建FileStream对象”);              
        sw3.Close ();
        fs3.Close ();
        //打开文件 只写
        FileStream fs4=File.OpenWrite(“TestFile.txt”); 
        StreamWriter sw4=new StreamWriter(fs4);
        sw4.WriteLine(“通过File.OpenWrite创建FileStream对象”);            
        sw4.Close ();
        fs4.Close ();
    }
    
    /// <summary>
    /// 二进制文件读写
    /// </summary>
    
    public void ByteReadWrite()
    {
             FileStream fs = new FileStream(“TestFile.txt”, FileMode.OpenOrCreate, FileAccess.ReadWrite);//创立文件 
             StreamWriter sw = new StreamWriter(fs);
              // 以文件情势写1个文书
             sw.WriteLine(“Hello, World”);
             sw.WriteLine(“你好吗?”);
             sw.WriteLine(“我很好!”);
             sw.WriteLine(“嘿嘿,示例好傻!”);
             sw.Flush();     //清理缓冲区
            StreamReader sr = new StreamReader(fs);
            sr.BaseStream.Seek(0, SeekOrigin.Begin);//定位到流的初叶地方 
            string str=string.Empty;
            while (!sr.EndOfStream)  //未到文件流结尾
            {
                 str+= sr.ReadLine();
            }
            BinaryReader br = new BinaryReader(fs);
            br.BaseStream.Seek(0, SeekOrigin.Begin);//定位到流的始发地点 
            Byte b = new Byte();
            while (br.PeekChar() > -一)//定位到下3个字符
            {
                b += br.ReadByte();
            }
             //关闭文件流
             sw.Close();
             br.Close();
             sr.Close();
             fs.Close();

鉴于常常应用文件处理,便自身包裹了下 分享给我们。 包涵写入文本 
批量删减文件  下载文件 。–可一向接纳

由于常常使用文件处理,便自身包装了下 分享给大家。 包涵写入文本 
批量刨除文件  下载文件 。–可间接运用

String str_read = sr.ReadToEnd(); ``//从开始到末尾读取文件的所有内容,str_read 存放的就是读取到的文本

   }
    
    public static void Main(string[] args)
    {
        FileOperate ofile=new FileOperate();
        //读取文件写入文件                
        ofile.WriteFromFileName();
        ofile.ReadFromFileName();
        ofile.WriteUseFileOrFileInfo();
        ofile.ReadUseFileOrFileInfo();
        ofile.WriteThroughFileStream();
        ofile.ReadThroughFileStream();
        ofile.ByteReadWrite();
        Console.ReadLine();
    }

/// <summary>
/// 写入到txt
/// </summary>
/// <param name=”savePath”></param>
/// <param name=”content”></param>
public static void WriteInTxt(string savePath, string content)
{
string tempPath = System.IO.Path.GetDirectoryName(savePath);
System.IO.Directory.CreateDirectory(tempPath); //创立近来文件目录
if (!System.IO.File.Exists(savePath))
{
FileStream fs一 = new FileStream(savePath, FileMode.Create,
FileAccess.Write);//创设写入文件
StreamWriter sw = new StreamWriter(fs1);
sw.WriteLine(content);//先导写入值
sw.Close();
fs1.Close();
}
else
{
FileStream fs = new FileStream(savePath, FileMode.Open,
FileAccess.Write);
StreamWriter sr = new StreamWriter(fs);
sr.WriteLine(content);//开首写入值
sr.Close();
fs.Close();
}
}

/// <summary>
/// 写入到txt
/// </summary>
/// <param name=”savePath”></param>
/// <param name=”content”></param>
public static void WriteInTxt(string savePath, string content)
{
string tempPath = System.IO.Path.GetDirectoryName(savePath);
System.IO.Directory.CreateDirectory(tempPath); //创造近来文件目录
if (!System.IO.File.Exists(savePath))
{
FileStream fs1 = new FileStream(savePath, FileMode.Create,
FileAccess.Write);//创建写入文件 
StreamWriter sw = new StreamWriter(fs1);
sw.WriteLine(content);//初阶写入值
sw.Close();
fs1.Close();
}
else
{
FileStream fs = new FileStream(savePath, FileMode.Open,
FileAccess.Write);
StreamWriter sr = new StreamWriter(fs);
sr.WriteLine(content);//起首写入值
sr.Close();
fs.Close();
}
}

sr.Close(); ``//读完文件记得关闭流

}

/// <summary>
/// 递归删除文件夹下全体文件
/// </summary>
/// <param name=”file”></param>
public static void DeleteFile(string dirPath)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(dirPath);
fileInfo.Attributes = FileAttributes.Normal &
FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(dirPath,
System.IO.FileAttributes.Normal);
//判断文件夹是还是不是还存在
if (Directory.Exists(dirPath))
{
foreach (string f in Directory.GetFileSystemEntries(dirPath))
{
if (File.Exists(f))
{
//倘使有子文件删除文件
File.Delete(f);
}
else
{
//循环递归删除子文件夹
DeleteFile(f);
}
}
//删除空文件夹
Directory.Delete(dirPath);
美高梅开户网址,}
}
catch (Exception e)
{

/// <summary>
/// 递归删除文件夹下全体文件
/// </summary>
/// <param name=”file”></param>
public static void DeleteFile(string dirPath)
{
try
{
//去除文件夹和子文件的只读属性
//去除文件夹的只读属性
System.IO.DirectoryInfo fileInfo = new DirectoryInfo(dirPath);
fileInfo.Attributes = FileAttributes.Normal &
FileAttributes.Directory;
//去除文件的只读属性
System.IO.File.SetAttributes(dirPath,
System.IO.FileAttributes.Normal);
//判断文件夹是不是还存在
if (Directory.Exists(dirPath))
{
foreach (string f in Directory.GetFileSystemEntries(dirPath))
{
if (File.Exists(f))
{
//借使有子文件删除文件
File.Delete(f);
}
else
{
//循环递归删除子文件夹 
DeleteFile(f);
}
}
//删除空文件夹 
Directory.Delete(dirPath);
}
}
catch (Exception e)
{

 

}
}

}
}

比方要一条一条读

/// <summary>
/// Http下载文件
/// </summary>
/// <param name=”url”>下载文件路径</param>
/// <param name=”savePath”>保存路径</param>
/// <returns></returns>
public static bool HttpDownloadFile(string url, string savePath)
{
string tempPath = System.IO.Path.GetDirectoryName(savePath);
System.IO.Directory.CreateDirectory(temp帕特h); //创设权且文件目录
string tempFile = tempPath + @”\” +
System.IO.Path.GetFileName(savePath); //目前文件
if (System.IO.File.Exists(tempFile))
{
//存在则跳出
return true;
//System.IO.File.Delete(tempFile);
}
try
{
FileStream fs = new FileStream(tempFile, FileMode.Append,
FileAccess.Write, FileShare.ReadWrite);
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//发送请求并获得相应回复数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才起来向目的网页发送Post请求
Stream responseStream = response.GetResponseStream();
//创制本三步跳件写入流
//Stream stream = new FileStream(tempFile, FileMode.Create);
byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, (int)bArr.Length);
while (size > 0)
{
//stream.Write(bArr, 0, size);
fs.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, (int)bArr.Length);
}
//stream.Close();
fs.Close();
responseStream.Close();
System.IO.File.Move(tempFile, savePath);
return true;
}
catch (Exception ex)
{
return false;
}
}

/// <summary>
/// Http下载文件
/// </summary>
/// <param name=”url”>下载文件路径</param>
/// <param name=”savePath”>保存路径</param>
/// <returns></returns>
public static bool HttpDownloadFile(string url, string savePath)
{
string tempPath = System.IO.Path.GetDirectoryName(savePath);
System.IO.Directory.CreateDirectory(tempPath); //制造权且文件目录
string tempFile = tempPath + @”\” +
System.IO.Path.GetFileName(savePath); //一时文件
if (System.IO.File.Exists(tempFile))
{
//存在则跳出
return true;
//System.IO.File.Delete(tempFile); 
}
try
{
FileStream fs = new FileStream(tempFile, FileMode.Append,
FileAccess.Write, FileShare.ReadWrite);
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//发送请求并收获相应回复数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才起来向目的网页发送Post请求
Stream responseStream = response.GetResponseStream();
//创造当和姑件写入流
//Stream stream = new FileStream(tempFile, FileMode.Create);
byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, (int)bArr.Length);
while (size > 0)
{
//stream.Write(bArr, 0, size);
fs.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, (int)bArr.Length);
}
//stream.Close();
fs.Close();
responseStream.Close();
System.IO.File.Move(tempFile, savePath);
return true;
}
catch (Exception ex)
{
return false;
}
}

while ((content = sr.ReadLine()) != null)//按行输出
{
f+=content;
}

 

写入文书档案方法

//FileMode.Append为不覆盖文件效果.create为掩盖
FileStream fs = new FileStream(path, mode: FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
//开端写入

sw.Write(“xxxxx”);
//清空缓冲区
sw.Flush();
//关闭
sw.Close();
fs.Close();

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图