C#创建文件,覆盖文件,读取文件

        /// 
        /// 指定路径创建文件
        /// 
        /// 路径
   public string CreateFile(string barcode, double weight)
        {
            try
            {
                 //指定文件夹路径
                string strPath = @"C:\Users\Public\PackageSharedInfo";
                //指定文件路径
                string strPath1 = @"C:\Users\Public\PackageSharedInfo\";
                string Tname = "当前输出 " + DateTime.Now.ToString() + "当前单号" + barcode + ",当前重量:" + weight;
                //判断文件夹是否存在,
                if (!Directory.Exists(strPath))
                {
                    //不存在则创建
                    Directory.CreateDirectory(strPath);
                }
             //创建文件
                using (FileStream fs = new FileStream(strPath1 + DateTime.Now.ToString("yyyyMMdd-hh") + ".txt", FileMode.Append))
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                    {
                        sw.WriteLine(Tname);
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                Logger.Error("程序异常,异常原因:" + ex);
                return "";
            }
        }

如果需要覆盖文本内容,可以将FileMode.Append修改为FileMode.Create。

///读取文件内容
   public bool GetContentByTxt()
        {
            //文件路径
            string path = @"C:\Users\Public\Libraries\ipc_channel.txt";
            //读取到的内容
            string conStr = "";
            try
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(fs);
                conStr = reader.ReadLine();
                //取状态
                string str1 = conStr.Remove(0, conStr.Length - 8);
                string str = str1.Remove(6, 2);
                Logger.Debug(str + "文件覆盖成功!");
                if (str == "resume")
                {
                    //逻辑处理,
                    return true;

                }
                else
                {
                   
                    return false;
                }
               
            }
            catch (Exception ex)
            {

                conStr = "";
                Logger.Error("程序异常,调用GetContentByTxt失败,异常原因+" + ex);
                return false;
            }
            
        }

你可能感兴趣的:(winform窗体,.NET,Web)