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

        /// <summary>
        /// 指定路径创建文件
        /// </summary>
        /// <param name="strPath">路径</param>
   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<TGKY>.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<TaiGuoKY>.Debug(str + "文件覆盖成功!");
                if (str == "resume")
                {
                    //逻辑处理,
                    return true;

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

                conStr = "";
                Logger<TaiGuoKY>.Error("程序异常,调用GetContentByTxt失败,异常原因+" + ex);
                return false;
            }
            
        }
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值