当前位置: 首页>>代码示例>>C#>>正文


C# FileStream.BeginWrite方法代码示例

本文整理汇总了C#中System.IO.FileStream.BeginWrite方法的典型用法代码示例。如果您正苦于以下问题:C# FileStream.BeginWrite方法的具体用法?C# FileStream.BeginWrite怎么用?C# FileStream.BeginWrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.FileStream的用法示例。


在下文中一共展示了FileStream.BeginWrite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ApplyIPSPatch

 public static void ApplyIPSPatch(string romname, string patchname)
 {
     // Noobish Noobsicle wrote this IPS patching code
     // romname is the original ROM, patchname is the patch to apply
     FileStream romstream = new FileStream(romname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
     FileStream ipsstream = new FileStream(patchname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
     int lint = (int)ipsstream.Length;
     byte[] ipsbyte = new byte[ipsstream.Length];
     byte[] rombyte = new byte[romstream.Length];
     IAsyncResult romresult;
     IAsyncResult ipsresult = ipsstream.BeginRead(ipsbyte, 0, lint, null, null);
     ipsstream.EndRead(ipsresult);
     int ipson = 5;
     int totalrepeats = 0;
     int offset = 0;
     bool keepgoing = true;
     while (keepgoing == true)
     {
         offset = ipsbyte[ipson] * 0x10000 + ipsbyte[ipson + 1] * 0x100 + ipsbyte[ipson + 2];
         ipson++;
         ipson++;
         ipson++;
         if (ipsbyte[ipson] * 256 + ipsbyte[ipson + 1] == 0)
         {
             ipson++;
             ipson++;
             totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1];
             ipson++;
             ipson++;
             byte[] repeatbyte = new byte[totalrepeats];
             for (int ontime = 0; ontime < totalrepeats; ontime++)
                 repeatbyte[ontime] = ipsbyte[ipson];
             romstream.Seek(offset, SeekOrigin.Begin);
             romresult = romstream.BeginWrite(repeatbyte, 0, totalrepeats, null, null);
             romstream.EndWrite(romresult);
             ipson++;
         }
         else
         {
             totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1];
             ipson++;
             ipson++;
             romstream.Seek(offset, SeekOrigin.Begin);
             romresult = romstream.BeginWrite(ipsbyte, ipson, totalrepeats, null, null);
             romstream.EndWrite(romresult);
             ipson = ipson + totalrepeats;
         }
         if (ipsbyte[ipson] == 69 && ipsbyte[ipson + 1] == 79 && ipsbyte[ipson + 2] == 70)
             keepgoing = false;
     }
     romstream.Close();
     ipsstream.Close();
 }
开发者ID:duckfist,项目名称:MM2Random,代码行数:53,代码来源:Patch.cs

示例2: APMWithFiles

 /// <summary>
 /// Demonstrates the use of the APM with files, through the FileStream class.
 /// This method performs asynchronous reads and writes to copy data from an input
 /// file to an output file.  Reads and writes are interlaced, and proceed in chunks
 /// of 8KB at a time (displaying progress to the console).
 /// </summary>
 static void APMWithFiles()
 {
     FileStream reader = new FileStream("sample.txt", FileMode.Open);
     FileStream writer = new FileStream("sample2.txt", FileMode.Create);
     byte[] buffer1 = new byte[8192], buffer2 = new byte[8192];
     IAsyncResult ar1, ar2 = null;
     while (true)
     {
         ar1 = reader.BeginRead(buffer1, 0, buffer1.Length, null, null);
         while (!ar1.IsCompleted)
         {
             Console.Write("R");
         }
         if (ar2 != null)
         {
             while (!ar2.IsCompleted)
             {
                 Console.Write("W");
             }
         }
         int bytesRead;
         if ((bytesRead = reader.EndRead(ar1)) == 0)
             break;  //No more data to read
         if (ar2 != null)
         {
             writer.EndWrite(ar2);
         }
         Array.Copy(buffer1, buffer2, bytesRead);
         ar2 = writer.BeginWrite(buffer2, 0, bytesRead, null, null);
     }
     Console.WriteLine();
     Console.WriteLine();
 }
开发者ID:Helen1987,项目名称:edu,代码行数:39,代码来源:APMExamples.cs

示例3: BeginProcessRequest

        public IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData) {

            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            StringBuilder builder = new StringBuilder();

            response.RedirectLocation = request.QueryString["uri"];
            response.StatusCode = 303;

            builder.AppendFormat("<request time='{0}' filePath='{1}'>", DateTime.Now, request.FilePath);

            IEnumerator enumerator = request.Headers.GetEnumerator();
            for (int i = 0; enumerator.MoveNext(); i++) {
                string name = request.Headers.AllKeys[i].ToString();
                builder.AppendFormat("<{0}>:{1}</{0}>", name, HttpUtility.HtmlEncode(request.Headers[name]));
            }

            builder.Append("</request>\r\n");

            byte[] output = Encoding.ASCII.GetBytes(builder.ToString());
            lock (m_lock) {
                m_file = new FileStream(request.MapPath("~/App_Data/TrackerLog.xml"), FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 1024, true);
                m_file.Seek(m_position, SeekOrigin.Begin);
                m_position += output.Length;
                return m_file.BeginWrite(output, 0, output.Length, cb, extraData);
            }
        }
开发者ID:xxjeng,项目名称:nuxleus,代码行数:27,代码来源:NuxleusHttpAsyncRedirectHandler.cs

示例4: BeginWriteThrowsForNegativeNumBytes

 public void BeginWriteThrowsForNegativeNumBytes()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<ArgumentOutOfRangeException>("numBytes", () => fs.BeginWrite(new byte[0], 0, -1, null, null));
     }
 }
开发者ID:geoffkizer,项目名称:corefx,代码行数:7,代码来源:BeginWrite.cs

示例5: BeginWriteThrowsForBadOffset

 public void BeginWriteThrowsForBadOffset(int arraySize, int offset, int numBytes)
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<ArgumentException>(() => fs.BeginWrite(new byte[arraySize], offset, numBytes, null, null));
     }
 }
开发者ID:geoffkizer,项目名称:corefx,代码行数:7,代码来源:BeginWrite.cs

示例6: WriteLog

 private void WriteLog(LogLevel level, string log)
 {
     var path = string.Format(@"{0}{1}\{2}", YFK.Core.Configuration.YFKConfig.Instance.WebSetting.LogPath, DateTime.Now.ToString("yyyy年MM月dd日"), level.ToString());
     if (path.Contains(":\\") == false)
     {
         if (System.Web.HttpContext.Current != null)
             path = System.Web.HttpContext.Current.Server.MapPath(path);
         else
             path = AppDomain.CurrentDomain.BaseDirectory + path;
     }
     var fileName = string.Format("{0}.txt", DateTime.Now.ToString("HH"));
     if (!Directory.Exists(path))
         Directory.CreateDirectory(path);
     using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Append, FileAccess.Write,
                                           FileShare.Write, 1024, FileOptions.Asynchronous))
     {
         log = string.Format("================记录时间:{0}================\r\n{1}\r\n",
             DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), log);
         byte[] buffer = System.Text.Encoding.UTF8.GetBytes(log + "\r\n");
         IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length,
             (asyncResult) =>
             {
                 var fStream = (FileStream)asyncResult.AsyncState;
                 fStream.EndWrite(asyncResult);
             },
             fs);
         fs.Close();
     }
 }
开发者ID:yimogit,项目名称:YimoFramework,代码行数:29,代码来源:FileLogger.cs

示例7: BeginWriteThrowsForNullArray

 public void BeginWriteThrowsForNullArray()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
     {
         Assert.Throws<ArgumentNullException>("array", () => fs.BeginWrite(null, 0, 0, null, null));
     }
 }
开发者ID:geoffkizer,项目名称:corefx,代码行数:7,代码来源:BeginWrite.cs

示例8: BeginPreRequestHandlerExecute

        IAsyncResult BeginPreRequestHandlerExecute (Object source, EventArgs e, AsyncCallback cb, Object state) {
            System.Web.HttpApplication app = (System.Web.HttpApplication)source;
            DateTime time = DateTime.Now;

            string line = String.Format(
                "{0,10:d}    {1,11:T}    {2, 32}   {3}\r\n",
                time, time,
                app.User.Identity.IsAuthenticated ?
                app.User.Identity.Name :
                app.Request.UserHostAddress,
                app.Request.Url);

            byte[] output = Encoding.ASCII.GetBytes(line);

            lock (_lock) {
                _file = new FileStream(
                    HttpContext.Current.Server.MapPath("~/App_Data/RequestLog.txt"),
                    FileMode.OpenOrCreate, FileAccess.Write,
                    FileShare.Write, 1024, true);

                _file.Seek(_position, SeekOrigin.Begin);
                _position += output.Length;
                return _file.BeginWrite(output, 0, output.Length, cb, state);
            }
        }
开发者ID:xxjeng,项目名称:nuxleus,代码行数:25,代码来源:AsyncRequestLogHttpModule.cs

示例9: FileAsync

        public FileAsync()
        {
            FileStream fs = new System.IO.FileStream ("test.txt",
                FileMode.Create, FileAccess.Write);

            fs.BeginWrite (new byte[10], 0, 0, FileWriteCallback, fs);

            // Hacemos mas acciones
        }
开发者ID:mariochavez,项目名称:Cesun-AppDistribuidas,代码行数:9,代码来源:FilaAsync.cs

示例10: AsyncFileStream

        public AsyncFileStream()
        {
            Console.WriteLine("Main Thread started. ThreadID = {0}", Thread.CurrentThread.GetHashCode());
             FileStream stream = new FileStream("logfile.txt", FileMode.Append, FileAccess.Write, FileShare.None, 4096, true);
             string msg = "This is a Test";
             byte[] buffer = Encoding.ASCII.GetBytes(msg);

             stream.BeginWrite(buffer, 0, buffer.Length, WriteDone, stream);
        }
开发者ID:ghostmonk,项目名称:CSharpTutorials,代码行数:9,代码来源:AsyncFileStream.cs

示例11: BeginWriteThrowsForClosed

        public void BeginWriteThrowsForClosed()
        {
            FileStream fs;
            using (fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
            {
            }

            Assert.Throws<ObjectDisposedException>(() => fs.BeginWrite(new byte[0], 0, 0, null, null));
        }
开发者ID:geoffkizer,项目名称:corefx,代码行数:9,代码来源:BeginWrite.cs

示例12: WriteContent

 private static void WriteContent(string file, string content)
 {
     var fileStream = new FileStream(file, FileMode.Truncate);
     var state = new FileState
     {
         FileStream = fileStream
     };
     var data = Encoding.ASCII.GetBytes(content);
     fileStream.BeginWrite(data, 0, data.Length, WriteDone, state);
 }
开发者ID:Wolfium,项目名称:ServiceStack.Extras,代码行数:10,代码来源:ReplaceInAllFiles.cs

示例13: BeginWriteThrowsForReadOnly

        public void BeginWriteThrowsForReadOnly()
        {
            string testPath = GetTestFilePath();
            using (FileStream fs = new FileStream(testPath, FileMode.Create, FileAccess.Write))
            {
            }

            using (FileStream fs = new FileStream(testPath, FileMode.Open, FileAccess.Read))
            {
                Assert.Throws<NotSupportedException>(() => fs.BeginWrite(new byte[0], 0, 0, null, null));
            }
        }
开发者ID:geoffkizer,项目名称:corefx,代码行数:12,代码来源:BeginWrite.cs

示例14: SaveFile

 public static string SaveFile(string name, byte[] bs)
 {
     int rtn = -1;
     try
     {
         string path = paths[ch.GetPrimary(name)]  + name;
         Log.Write("保存文件路径:" + path);
         FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite, 8192, FileOptions.WriteThrough | FileOptions.Asynchronous);
         IAsyncResult ir = fs.BeginWrite(bs, 0, bs.Length, WriteCallback, fs);
     }
     catch (Exception e)
     {
         Log.Error("FileHelper.SaveFile:" + e.Message);
     }
     return name;
 }
开发者ID:kcitwm,项目名称:dova,代码行数:16,代码来源:FileHelper.cs

示例15: using

        public void СохранитьФайл(string Проект, string Каталог, string Файл, string Содержание)
        {
            Interlocked.Increment(ref КоличествоФайловВсего);
            var ИмяФайла = ПолучитьИПроверитьДиректорию(Проект, Каталог) + "\\" + Файл;
            var Кодировка = ВыборКодировки(Файл);
            var Сигнатура = Кодировка.GetPreamble();
            Содержание = ЗаменитьТокены(Содержание);

            var НовыйПоток = СложитьДваПотока(Сигнатура,Кодировка.GetBytes(Содержание));

            var СтарыйПоток = new byte[0];
            if (File.Exists(ИмяФайла))
            {
                СтарыйПоток = File.ReadAllBytes(ИмяФайла);
            }
            var ЗаписыватьФайл = НовыйПоток.Length != СтарыйПоток.Length;
            if (!ЗаписыватьФайл)
            {
                ЗаписыватьФайл = !CRC.ПотокиИдентичны(НовыйПоток, СтарыйПоток);
            }
            //ЗаписыватьФайл = true;
            if (!ЗаписыватьФайл)
            {
                return;
            }
            Interlocked.Increment(ref КоличествоФайловКЗаписи);
            //File.WriteAllBytes(ИмяФайла, НовыйПоток);
            //Interlocked.Increment(ref КоличествоФайловЗаписано);
            ИзменитьАтрибутЧтенияФайла(ИмяФайла, false);
            try
            {
                using (var ПотокФайла = new FileStream(ИмяФайла, FileMode.Create, FileAccess.Write, FileShare.Write, 4096, true))
                {
                    var МаркерВызова = ПотокФайла.BeginWrite(НовыйПоток, 0, НовыйПоток.Length, ОбратныйВызовСохраненияФайла, ИмяФайла);
                    Ожидания.Add(МаркерВызова.AsyncWaitHandle);
                }
            }
            catch (Exception Исключение)
            {
                if (Interlocked.Increment(ref КоличествоОшибокЗаписи) < 10)
                {
                    var Сообщение = ((Исключение.InnerException == null)? Исключение.Message: Исключение.InnerException.Message);
                    Console.WriteLine(Сообщение);
                }
            }
        }
开发者ID:Rugut,项目名称:UPP,代码行数:46,代码来源:СохранениеПроекта.cs


注:本文中的System.IO.FileStream.BeginWrite方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。