zoukankan      html  css  js  c++  java
  • c#读取并异步写入文件

    1.同步读取和写入

      StreamReader objReader = new StreamReader("E://workspace//zzz//read.txt", Encoding.GetEncoding("utf-8"));
                string sLine = "";
                ArrayList LineList = new ArrayList();
                while (sLine != null)
                {
                    sLine = objReader.ReadLine();
                    if (sLine != null && !sLine.Equals(""))
                        LineList.Add(sLine);
                }
                objReader.Close();
    
                string str = "";
                foreach (var item in LineList)
                {
                    str += item + Environment.NewLine;
                }
                string filePath = "E://workspace//zzz//" + DateTime.Now.Millisecond + ".txt";
                FileStream fs = new FileStream(filePath, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("utf-8"));
                //开始写入
                sw.Write(str);
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();
    

      2.异步写入

     /// <summary>
            /// 异步将xml内容写入文件
            /// </summary>
            /// <param name="str"></param>
            /// <param name="encoding"></param>
            public static void XmlToFile(string str, string fileName, string encoding)
            {
                string filePath = "E://workspace_VS//zzz//" + fileName + DateTime.Now + ".xml";
                byte[] bytes = Encoding.GetEncoding(encoding).GetBytes(str.ToString());
                FileStream writer = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                writer.BeginWrite(bytes, 0, str.Length, new AsyncCallback(endWrite), writer);
            }
            /// <summary>
            /// 结束异步写入
            /// </summary>
            /// <param name="asr"></param>
            private static void endWrite(IAsyncResult asr)
            {
                using (Stream str = (Stream)asr.AsyncState)
                {
                    str.EndWrite(asr);
                }
            }
    

      

  • 相关阅读:
    div在IOS系统和安卓系统位置不同
    js操作样式
    Css设置文字旋转
    textarea高度自适应
    html引入html页面
    举例说明$POST 、$HTTP_RAW_POST_DATA、php://input三者之间的区别
    PHP获取POST的几种方法
    PHP以xml形式获取POST数据
    使用Composer安装Symfony
    php如何以post形式发送xm并返回xmll数据
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/13278465.html
Copyright © 2011-2022 走看看