C#写入文件,与读取文件内容

本文介绍了一个简单的文件读写方法实现,包括如何写入文件及从文件中读取内容。通过使用C#语言,实现了文件路径的映射、目录创建、文件创建及内容写入,并考虑了异常处理。
/// <summary>
    /// 写文件
    /// </summary>
    /// <param name="Path">文件路径</param>
    /// <param name="Name">文件名(包括后缀名)</param>
    /// <param name="content">内容</param>
    /// <returns></returns>
    public static bool WriteFile(string Path, string Name, string content)
    {
        try
        {
            string path = HttpContext.Current.Server.MapPath(Path);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fname = HttpContext.Current.Server.MapPath(Path + "/" + Name);
            if (!File.Exists(fname))
            {
                FileStream fs = File.Create(fname);
                fs.Close();
            }
            StreamWriter sw = new StreamWriter(fname, false, System.Text.Encoding.GetEncoding("utf-8"));
            sw.WriteLine(content);
            sw.Close();
            sw.Dispose();
            return true;
        }
        catch
        {
            return false;
        }
    }

    /// <summary>
    /// 读文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <returns></returns>
    public static string ReadFile(string Path)
    {
        try
        {
            StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath(Path), System.Text.Encoding.GetEncoding("utf-8"));
            string content = sr.ReadToEnd().ToString();
            sr.Close();
            return content;
        }
        catch
        {
            return "<span style='color:red; font-size:x-large;'>Sorry,The Ariticle wasn't found!! It may have been deleted accidentally from Server.</span>";
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值