C# 下载文件 删除文件 写入文本【分分快三计划】

作者:编程技术

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

分分快三计划 1分分快三计划 2Code
using System;
using System.IO;
/*从文本文件中读或许写文本时,首先需创建二个与公事有关的StreamReader或然StreamWriter对象
 每贰个StreamReader或StreamWriter对象都与一种字符编码格局有关。私下认可UTF8Encoding
*/
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>
    /// 方法3:通过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方法:会去除已经存在的文件
    /// 劣势:只可以创立帮助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);
        sw1.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);
              // 以文件格局写贰个文件
             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();

/// <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)
{

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

   }
    
    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>
/// 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>
/// 写入到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(); ``//读完文件记得关闭流

}
}

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

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

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

本文由分分快三计划发布,转载请注明来源

关键词: 分分快三计划 .NET C#数据结构 C# 写入文本 C# 下载