一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net中读写文件实现代码

时间:2011-12-26 编辑:简简单单 来源:一聚教程网

写入分为续写和覆盖 只需改变第一个参数的值就可切换

代码如下:

  

 代码如下 复制代码

///


        /// 内容写入到文本文件
        ///

        /// 状态,判断是续写还是覆盖
        /// 文件名称
        /// 内容
        /// 返回错误信息或时1代表写入成功
        public static  string writeFile(bool bl,string fileName, string content)
        {
            try
            {
                string pathName = System.Web.HttpContext.Current.Server.MapPath(fileName);
                //这个不存在会自动创建
                using (StreamWriter sw = new StreamWriter(pathName, bl, Encoding.Default))
                {
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "1";
        }

        ///


        /// 读取文本文件内容
        ///

        /// 文件名称
        /// 返回内容
        public static  string readFile(string fileName)
        {
            string result = "";
            try
            {
                string pathName = System.Web.HttpContext.Current.Server.MapPath(fileName);
                using (StreamReader sr = new StreamReader(pathName, Encoding.Default))
                {
                    result = sr.ReadToEnd();
                    sr.Close();
                }
            }
            catch (Exception ex)
            {
                return "0";//ex.Message;
            }
            return result;
        }

热门栏目