c# 讀/寫檔案(各種格式)

來源:互聯網
上載者:User

   最簡單的:

--------寫
//content是要寫入文本的字串
//(@txtPath + @"\" + rid + ".txt");要被寫入的TXT
 StreamWriter sw = new StreamWriter(@txtPath + @"\" + rid + ".txt");
 sw.WriteLine(content);
 sw.Close();
---------讀
//folder被讀取的檔案路徑
text = File.ReadAllText(folder, System.Text.Encoding.GetEncoding("gb2312"));

-------寫入流
            //將string寫入檔案    
            try
                {
                    FileStream fs = new FileStream(@"d:\資料處理\法規20080116HTML\" + Actid.ToString() + ".html", FileMode.OpenOrCreate, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
                    sw.Flush();
                    sw.BaseStream.Seek(0, SeekOrigin.Begin);
                    sw.Write(pageContent);
                    sw.Close();
                }
                catch (Exception ex) { }
//HTTP嚮應後寫出檔案

HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
WebResponse result = null;
try
{
    myWebRequest = (HttpWebRequest)WebRequest.Create(Url);
    result = myWebRequest.GetResponse();
    Stream response = result.GetResponseStream();
    byte[] bytes = new byte[10240];
    int n = 1;

    FileStream fs = File.Create(@"d:\資料處理\法規20080116HTML\" + Actid.ToString() + ".html");
    while (n > 0)
    {
        n = response.Read(bytes, 0, 10240);
        fs.Write(bytes, 0, n);
    }
    response.Close();
    fs.Close();
}
catch (Exception ex) { }

//讀取

string FileContent = File.ReadAllText(path, System.Text.Encoding.GetEncoding("gb2312"));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.