C#读写文件方法

    ///////////////////////读写文件方法
    /// <summary>
    /// 将content内容写入到filepath文件中
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <param name="content">写入的内容</param>
    static void WriteFile(String filePath, String content)
    {
        //FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
        //var buffer = Encoding.Default.GetBytes(content);
        //fs.Write(buffer, 0, buffer.Length);
        //fs.Flush();
        //fs.Close();
        FileStream fs = new FileStream(System.Web.HttpContext.Current.Server.MapPath(filePath), FileMode.CreateNew);
        StreamWriter sw = new StreamWriter(fs);
        sw.Write(content);
        sw.Flush(); // 清除读写缓冲区
        sw.Close();
    }
    
    //读取txt文件的内容
    public string readFile(string strfile)
    {
        string strout;
        strout = "";
        if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(strfile)))
        {
        }
        else
        {
            StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(strfile), System.Text.Encoding.Default);
            String input = sr.ReadToEnd();
            sr.Close();
            strout = input;
        }
        return strout;
    }
然后插入一个按钮,则在网站根目录(Web目录)的
OutputFile文件夹中写入文本文档K.txt
protected void btcreate_Click(object sender, EventArgs e)
{
        //K.txt
        WriteFile("/OutputFile/K.txt", TextBox1.Text);
}
注意:  /  表示网站根目录

 

 

 

posted @ 2015-01-29 15:06  Bella工作坊  阅读(188)  评论(0编辑  收藏  举报