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

金沙注册送58 1金沙注册送58 2Code
using System;
using System.IO;
/*从文本文件中读可能写文本时,首先需创造1个与公事有关的StreamReader只怕StreamWriter对象
 每三个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>
    ///方法二: 使用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)
        {
            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>
    /// 方法一:通过文件名创制
    /// </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方法:会去除已经存在的文件
    /// 缺点:只可以创设扶助UTF八Encoding的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>
    /// 2进制文件读写
    /// </summary>
    
    public void ByteReadWrite()
    {
             FileStream fs = new FileStream(“TestFile.txt”, FileMode.OpenOrCreate, FileAccess.ReadWrite);//创立文件 
             StreamWriter sw = new StreamWriter(fs);
              // 以文件情势写三个文书
             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() > -1)//定位到下三个字符
            {
                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 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();
}
}

/// <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
金沙注册送58 ,{
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(tempPath); //成立一时半刻文件目录
string tempFile = tempPath + @”\” +
System.IO.帕特h.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(save帕特h); //一时半刻文件
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地图