Flush() public method

Clears buffers for this stream and causes any buffered data to be written to the file.
public Flush ( ) : void
return void
Example #1
0
        //Đưa SecretKey vào File của thuật toán 3DES
        public void AddSecretKeytoFile(string inputFile)
        {
            //Add SecretKey to File;
            if (File.Exists(inputFile))
            {
                FileStream fsOpen = new FileStream(inputFile, FileMode.Open, FileAccess.ReadWrite);
                try
                {
                    byte[] content = new byte[fsOpen.Length];
                    fsOpen.Read(content, 0, content.Length);
                    //string sContent = System.Text.Encoding.UTF8.GetString(content); //noi dung bang string

                    //byte[] plainbytesCheck = System.Text.Encoding.UTF8.GetBytes(sContent);
                    byte[] plainbytesKey = new UTF8Encoding(true).GetBytes(m_EncryptedSecretKey + "\r\n");

                    fsOpen.Seek(0, SeekOrigin.Begin);
                    fsOpen.Write(plainbytesKey, 0, plainbytesKey.Length);
                    fsOpen.Flush();
                    fsOpen.Write(content, 0, content.Length);
                    fsOpen.Flush();
                    fsOpen.Close();
                }
                catch
                {
                    fsOpen.Close();
                }
            }
        }
Example #2
0
        public static void DecompressFileLZMA(string inFile, string outFile)
        {
            SevenZip.Sdk.Compression.Lzma.Decoder coder = new SevenZip.Sdk.Compression.Lzma.Decoder();
            FileStream input = new FileStream(inFile, FileMode.Open);
            FileStream output = new FileStream(outFile, FileMode.Create);

            // Read the decoder properties
            byte[] properties = new byte[5];
            input.Read(properties, 0, 5);

            // Read in the decompress file size.
            byte[] fileLengthBytes = new byte[8];
            input.Read(fileLengthBytes, 0, 8);
            long fileLength = BitConverter.ToInt64(fileLengthBytes, 0);

            coder.SetDecoderProperties(properties);
            coder.Code(input, output, input.Length, fileLength, null);
            output.Flush();
            output.Close();

            try
            {
                output.Flush();
                output.Close();

                input.Flush();
                input.Close();
            }
            catch
            {
            }
        }
        public double Execute(DirectoryInfo targetDirectory, int sizeHintInMb)
        {
            double result   = 0.0;
            var file        = GetBenchmarkFile(targetDirectory);

            if (file.Exists)
            {
                file.Delete();
            }

            using (var fileStream = new FileStream(file.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                var sizeInBytes = (long) sizeHintInMb*1000L*1000L;

                OnPrepare(fileStream, sizeInBytes);
                fileStream.Flush();
                fileStream.Seek(0L, SeekOrigin.Begin);

                var stopwatch = new Stopwatch();
                stopwatch.Start();

                var actualSizeInBytes = OnExecute(fileStream,sizeInBytes);
                fileStream.Flush(true);

                stopwatch.Stop();
                result = ((double) actualSizeInBytes/stopwatch.Elapsed.TotalSeconds)/(1000.0*1000.0);
            }

            if (file.Exists)
            {
                file.Delete();
            }

            return result;
        }
        public void FlushSetLengthAtEndOfBuffer()
        {
            // This is a regression test for a bug with FileStream’s Flush() 
            // and SetLength() methods.
            // The read-buffer was not flushed inside Flush and SetLength when
            // the buffer pointer was at the end. This causes subsequent Seek 
            // and Read calls to operate on stale/wrong data.


            // customer reported repro
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.SetLength(200);
                fs.Flush();

                // write 119 bytes starting from Pos = 28 
                fs.Seek(28, SeekOrigin.Begin);
                Byte[] buffer = new Byte[119];
                for (int i = 0; i < buffer.Length; i++)
                    buffer[i] = Byte.MaxValue;
                fs.Write(buffer, 0, buffer.Length);
                fs.Flush();

                // read 317 bytes starting from Pos = 84;
                fs.Seek(84, SeekOrigin.Begin);
                fs.Read(new byte[1024], 0, 317);

                fs.SetLength(135);
                fs.Flush();

                // read one byte at Pos = 97
                fs.Seek(97, SeekOrigin.Begin);
                Assert.Equal(fs.ReadByte(), (int)Byte.MaxValue);
            }
        }
Example #5
0
 public void FlushThrowsForDisposedStream()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
     {
         fs.Dispose();
         Assert.Throws<ObjectDisposedException>(() => fs.Flush(false));
         Assert.Throws<ObjectDisposedException>(() => fs.Flush(true));
     }
 }
Example #6
0
        public void BasicFlushFunctionality()
        {
            using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
            {
                fs.WriteByte(0);
                fs.Flush(false);

                fs.WriteByte(0xFF);
                fs.Flush(true);
            }
        }
Example #7
0
 /// <summary>
 /// 文件的复制
 /// </summary>
 /// <param FormerFile="string">源文件路径</param>
 /// <param toFile="string">目的文件路径</param> 
 /// <param SectSize="int">传输大小</param> 
 /// <param progressBar="ProgressBar">ProgressBar控件</param> 
 public void CopyFile(string FormerFile, string toFile, int SectSize, ProgressBar progressBar1)
 {
     progressBar1.Value = 0;//设置进度栏的当前位置为0
     progressBar1.Minimum = 0;//设置进度栏的最小值为0
     FileStream fileToCreate = new FileStream(toFile, FileMode.Create);//创建目的文件,如果已存在将被覆盖
     fileToCreate.Close();//关闭所有资源
     fileToCreate.Dispose();//释放所有资源
     FormerOpen = new FileStream(FormerFile, FileMode.Open, FileAccess.Read);//以只读方式打开源文件
     ToFileOpen = new FileStream(toFile, FileMode.Append, FileAccess.Write);//以写方式打开目的文件
     int max = Convert.ToInt32(Math.Ceiling((double)FormerOpen.Length / (double)SectSize));//根据一次传输的大小,计算传输的个数
     progressBar1.Maximum = max;//设置进度栏的最大值
     int FileSize;//要拷贝的文件的大小
     if (SectSize < FormerOpen.Length)//如果分段拷贝,即每次拷贝内容小于文件总长度
     {
         byte[] buffer = new byte[SectSize];//根据传输的大小,定义一个字节数组
         int copied = 0;//记录传输的大小
         int tem_n = 1;//设置进度栏中进度块的增加个数
         while (copied <= ((int)FormerOpen.Length - SectSize))//拷贝主体部分
         {
             FileSize = FormerOpen.Read(buffer, 0, SectSize);//从0开始读,每次最大读SectSize
             FormerOpen.Flush();//清空缓存
             ToFileOpen.Write(buffer, 0, SectSize);//向目的文件写入字节
             ToFileOpen.Flush();//清空缓存
             ToFileOpen.Position = FormerOpen.Position;//使源文件和目的文件流的位置相同
             copied += FileSize;//记录已拷贝的大小
             progressBar1.Value = progressBar1.Value + tem_n;//增加进度栏的进度块
         }
         int left = (int)FormerOpen.Length - copied;//获取剩余大小
         FileSize = FormerOpen.Read(buffer, 0, left);//读取剩余的字节
         FormerOpen.Flush();//清空缓存
         ToFileOpen.Write(buffer, 0, left);//写入剩余的部分
         ToFileOpen.Flush();//清空缓存
     }
     else//如果整体拷贝,即每次拷贝内容大于文件总长度
     {
         byte[] buffer = new byte[FormerOpen.Length];//获取文件的大小
         FormerOpen.Read(buffer, 0, (int)FormerOpen.Length);//读取源文件的字节
         FormerOpen.Flush();//清空缓存
         ToFileOpen.Write(buffer, 0, (int)FormerOpen.Length);//写放字节
         ToFileOpen.Flush();//清空缓存
     }
     FormerOpen.Close();//释放所有资源
     ToFileOpen.Close();//释放所有资源
     if (MessageBox.Show("复制完成") == DialogResult.OK)//显示"复制完成"提示对话框
     {
         progressBar1.Value = 0;//设置进度栏的当有位置为0
         textBox1.Clear();//清空文本
         textBox2.Clear();
         str = "";
     }
 }
Example #8
0
        public void FlushOnReadOnlyFileDoesNotThrow()
        {
            string fileName = GetTestFilePath();
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                fs.WriteByte(0);
            }

            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                fs.Flush(false);
                fs.Flush(true);
            }
        }
Example #9
0
 /// <summary>Renders the body of the rule file in pseudo-code HTML.</summary>
 /// <param name="fileName">Output file name to generate.</param>
 /// <param name="title">Title for the HTML page.
 /// If null, the default value defined in pseudocode_body.xsl will be used.</param>
 public void RenderBody(string fileName, string title)
 {
     FileStream fs = new FileStream(fileName, FileMode.Create);
     RenderBody(fs, title);
     fs.Flush();
     fs.Close();
 }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Shapes();

            // Load the PPTX to Presentation object
            Presentation pres = new Presentation(dataDir + "AccessingOLEObjectFrame.pptx");

            // Access the first slide
            ISlide sld = pres.Slides[0];

            // Cast the shape to OleObjectFrame
            OleObjectFrame oof = (OleObjectFrame)sld.Shapes[0];

            // Read the OLE Object and write it to disk
            if (oof != null)
            {
                FileStream fstr = new FileStream(dataDir+ "excelFromOLE_out.xlsx", FileMode.Create, FileAccess.Write);
                byte[] buf = oof.ObjectData;
                fstr.Write(buf, 0, buf.Length);
                fstr.Flush();
                fstr.Close();
            }
            
            
        }
        /// <summary>
        /// Save batches and the header.
        /// </summary>
        /// <param name="batchList">BatchList to save</param>
        /// <param name="header">Header information</param>
        public void SaveBatches(List<Batch> batchList, BatchHeader header)
        {
            // Create the batch directory.
            var path = Path.Combine(_batchSpoolDirectory, header.BatchCode.ToString());
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            foreach (var b in batchList)
            {
                string filePath = Path.Combine(path, b.FileName);
                var formatter = new BinaryFormatter();
                using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    formatter.Serialize(fileStream, b);
                    fileStream.Flush();
                }
            }

            string headerFilePath = Path.Combine(path, BATCH_HEADER_FILENAME);
            var headerFormatter = new BinaryFormatter();
            using (var fileStream = new FileStream(headerFilePath, FileMode.Create, FileAccess.ReadWrite))
            {
                headerFormatter.Serialize(fileStream, header);
                fileStream.Flush();
            }
        }
Example #12
0
        private bool TestWrite(FileStream fs, int BufferLength, int BytesToWrite, int Offset)
        {
            bool result = true;
            long startLength = fs.Position;
            long nextbyte = startLength % 256;

            byte[] byteBuffer = new byte[BufferLength];
            for (int i = Offset; i < (Offset + BytesToWrite); i++)
            {
                byteBuffer[i] = (byte)nextbyte;

                // Reset if wraps past 255
                if (++nextbyte > 255)
                    nextbyte = 0;
            }

            fs.Write(byteBuffer, Offset, BytesToWrite);
            fs.Flush();
            if ((startLength + BytesToWrite) < fs.Length)
            {
                result = false;
                Log.Exception("Expeceted final length of " + (startLength + BytesToWrite) + " bytes, but got " + fs.Length + " bytes");
            }
            return result;
        }
    public void Init() {
      _sign=Topic.root.Get("/etc/PersistentStorage");
      _verbose=_sign.Get("verbose");
      _verbose.config=true;

      if(!Directory.Exists("../data")) {
        Directory.CreateDirectory("../data");
      }
      _file=new FileStream("../data/persist.xdb", FileMode.OpenOrCreate, FileAccess.ReadWrite);
      if(_file.Length<=0x40) {
        _file.Write(new byte[0x40], 0, 0x40);
        _file.Flush(true);
        _nextBak=DateTime.Now.AddHours(1);
      } else {
        Load();
      }
      _fileLength=_file.Length;
      _work=new AutoResetEvent(false);
      _thread=new Thread(new ThreadStart(PrThread));
      _thread.Priority=ThreadPriority.BelowNormal;
      _now=DateTime.Now;
      if(_nextBak<_now) {
        Backup();
      }
      _thread.Start();
      Topic.root.all.changed+=MqChanged;
    }
Example #14
0
        private void DoDownload(string source, string output)
        {
            WebRequest req = WebRequest.Create(source);
            WebResponse rsp = req.GetResponse();
            Stream stream = rsp.GetResponseStream();

            string path = Path.GetDirectoryName(output);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using (var fs = new FileStream(output, FileMode.Create))
            {
                int readCount = -1;
                var buffer = new byte[1024*64];
                while (readCount != 0)
                {
                    readCount = stream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, readCount);
                }

                fs.Flush();
            }
            _logger.InfoLine(source + " ==> " + output);
        }
Example #15
0
        public void TestGetPolicySetBytes()
        {
            string testFilename = Path.Combine(m_testPath, "Has everthing.policy");
            string outputFilename = Path.Combine(m_testPath, "TestGetPolicySetBytes.policy");
            try
            {
                PolicySetItem policySetItem = ReadPolicySet(testFilename);
                IPolicySet policySet = policySetItem.Data;

                byte[] rhsBytes = PolicySuites.Instance.GetPolicySetBytes(policySet, SaveOption.SaveOnly);
                Assert.IsTrue(0 < rhsBytes.Length, "Expected the rhs to contain bytes after a read");

                using(FileStream outStream = new FileStream(outputFilename, FileMode.Create))
                {
                    outStream.Write(rhsBytes, 0, (int)rhsBytes.Length);
                    outStream.Flush();
                }

                Assert.IsTrue(File.Exists(outputFilename));

                PolicySetItem resultantPolicySetItem = ReadPolicySet(outputFilename);
                IPolicySet resultantPolicySet = resultantPolicySetItem.Data;
                Assert.IsNotNull(resultantPolicySet);

                AreEquivalent(policySetItem, resultantPolicySetItem);
            }
            finally
            {
                if (File.Exists(outputFilename))
                    File.Delete(outputFilename);
            }
        }
        public HttpResponseMessage Add(List<Gallery> items)
        {
            try
            {
                foreach (var item in items)
                {
                    List<string> content = item.Content.Split(',').ToList();
                    var bytes = Convert.FromBase64String(content[1]);
                    string mappath = HttpContext.Current.Server.MapPath("~/Assets/img/gallery/");
                    var filepath = Path.Combine(mappath, item.Name);
                    //string filepath = String.Format(mappath + "{0}", item.Name);
                    using (var imageFile = new FileStream(filepath, FileMode.Create))
                    {
                        imageFile.Write(bytes, 0, bytes.Length);
                        imageFile.Flush();
                    }

                    item.Content = String.Format("Assets/img/gallery/{0}", item.Name);
                }
                using (var db = new DBContext())
                {
                    db.Galleries.AddRange(items);
                    db.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.Accepted);
                }

            }
            catch (Exception ex)
            {
              return  Request.CreateResponse(HttpStatusCode.BadRequest,ex.Message);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string filename = this.filename.Text;
            string path = System.AppDomain.CurrentDomain.BaseDirectory + @"\client\";
            bool issuccess = false;
            string message = "";
            Stream filestream = new MemoryStream();
            long filesize = client.DownLoadFile(filename, out issuccess, out message, out filestream);
            if (issuccess)
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                byte[] buffer = new byte[filesize];
                FileStream fs = new FileStream(path + filename, FileMode.Create, FileAccess.Write);
                int count = 0;
                while ((count = filestream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fs.Write(buffer, 0, count);
                }
                //清空缓冲区
                fs.Flush();
                //关闭流
                fs.Close();
                MessageBox.Show("下载成功!");
            }
            else
            {
                MessageBox.Show(message);

            }

        }
Example #18
0
        //写备份文件
        public bool WriteFile(string FileName,string[] str)
        {
            try
            {
                FileStream fs = new FileStream(FileName,FileMode.OpenOrCreate|FileMode.Append,FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);

                string msg;
                for (int i = 0; i < str.Length - 1; i++)
                {
                    //加密数据
                    msg = Converts(str[i]);
                    sw.WriteLine(msg);
                }

                fs.Flush();
                sw.Close();
                fs.Close();

                return true;
            }
            catch (Exception Ex)
            {
                return false;
            }
        }
Example #19
0
 private static Cursor LoadCursorFromResource(string resourceName)
 {
     Cursor result;
     try
     {
         var tempFile = Path.GetTempFileName();
         using (Stream s =
             Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
         using (var resourceFile = new FileStream(tempFile, FileMode.Create))
         {
             if (s != null)
             {
                 var b = new byte[s.Length + 1];
                 s.Read(b, 0, Convert.ToInt32(s.Length));
                 resourceFile.Write(b, 0, Convert.ToInt32(b.Length - 1));
             }
             resourceFile.Flush();
         }
         result = new Cursor(NativeMethods.LoadCursorFromFile(tempFile));
         File.Delete(tempFile);
     }
     catch
     {
         result = Cursors.Cross;
     }
     return result;
 }
        public ActionResult Crop()
        {
            var imagem_url = Request.Form["url"];
            var x1 = int.Parse(Request.Form["x1"]);
            var x2 = int.Parse(Request.Form["x2"]);
            var y1 = int.Parse(Request.Form["y1"]);
            var y2 = int.Parse(Request.Form["y2"]);
            var nomeFinal = "../uploads/imagem_crop" + Path.GetExtension(imagem_url);

            using (var response = new StreamReader(Server.MapPath(imagem_url))) {
                    Bitmap imagem = new Bitmap(response.BaseStream);

                    int largura = x2 - x1;
                    int altura = y2 - y1;

                    Bitmap target = new Bitmap(largura, altura);
                    Rectangle cropRect = new Rectangle(x1, y1, largura, altura);

                    using (Graphics g = Graphics.FromImage(target)) {
                        g.DrawImage(imagem, new Rectangle(0, 0, largura, altura), cropRect, GraphicsUnit.Pixel);
                        using (var fileStream = new FileStream(Server.MapPath(nomeFinal), FileMode.OpenOrCreate)) {
                            target.Save(fileStream, imagem.RawFormat);
                            fileStream.Flush();
                        }
                    }
            }

            return Json(new { imagem_recortada = nomeFinal });
        }
        public void doBackUp()
        {
            try
            {
                string path = @"C:\";
                string newpath = System.IO.Path.Combine(path, "BackUpLocation");
                Directory.CreateDirectory(newpath);

                FileStream fmdf = new FileStream(mdf, FileMode.Open, FileAccess.Read);
                FileStream fldf = new FileStream(ldf, FileMode.Open, FileAccess.Read);
                FileStream fbak = new FileStream(bak, FileMode.Create, FileAccess.Write);

                byte[] fmcontent = new byte[fmdf.Length];
                fmdf.Read(fmcontent, 0, (int)fmdf.Length);
                fbak.Write(fmcontent, 0, (int)fmdf.Length);

                byte[] sym = new byte[3];
                sym[0] = (byte)'$'; sym[1] = (byte)'*'; sym[2] = (byte)'^';
                fbak.Write(sym, 0, 3);

                byte[] flcontent = new byte[fldf.Length];
                fldf.Read(flcontent, 0, (int)fldf.Length);
                fbak.Write(flcontent, 0, (int)fldf.Length);

                fbak.Flush();
                fbak.Close();
                fmdf.Close();
                fldf.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #22
0
 public static bool DownLoadXml(string fileID, string filePath)
 {
     bool ret = true;
     string errMsg="";
     try
     {
         OleDbConnection db2conn = new OleDbConnection(DBdb2.SetConString());
         string sqlstr = "select * from T_SYS_MENU where T_XMLID='" + fileID + "'";
         OleDbCommand db2cmd = new OleDbCommand(sqlstr, db2conn);
         db2conn.Open();
         OleDbDataReader db2reader = db2cmd.ExecuteReader();
         string FileName = filePath;
         if (!db2reader.Read())
         {
             FileName = "";
         }
         else
         {
             byte[] bytes = (byte[])db2reader["B_XML"];
             FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
             fs.Write(bytes, 0, bytes.Length);
             fs.Flush();
             fs.Close();
         }
         db2reader.Close();
         db2cmd.Dispose();
         db2conn.Close();
     }
     catch (Exception ce)
     {
         errMsg = ce.Message;
         ret = false;
     }
     return ret;
 }
Example #23
0
File: Wallpaper.cs Project: v0l/whp
 public static void Set(Uri uri)
 {
     if (!Directory.Exists("C:\\WHP\\imgs"))
     {
         Directory.CreateDirectory("C:\\WHP\\imgs");
     }
     string path = uri.ToString().Substring(uri.ToString().LastIndexOf("/") + 1);
     string text = Path.Combine("C:\\WHP\\imgs", path);
     if (!File.Exists(text))
     {
         try
         {
             HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri.ToString());
             httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36";
             using (Stream responseStream = httpWebRequest.GetResponse().GetResponseStream())
             {
                 using (FileStream fileStream = new FileStream(text, FileMode.Create, FileAccess.ReadWrite))
                 {
                     responseStream.CopyTo(fileStream);
                     fileStream.Flush();
                 }
             }
         }
         catch
         {
             return;
         }
     }
     Wallpaper.SystemParametersInfo(20, 0, text, 3);
 }
Example #24
0
        public static SettingDocument Open()
        {
            SettingDocument document = new SettingDocument();
            XElement root;

            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                root = XDocument.Load(fs).Root;
                fs.Flush();
                fs.Close();
            }
            byte[] entropy = Convert.FromBase64String(root.Attribute("entropy").Value);

            document.ConnectUri = new Uri(root.Element("Uri").Value);
            document.UserName = Decrypt(entropy, root.Element("UserName").Value);
            document.Password = Decrypt(entropy, root.Element("Password").Value);
            document.BugFilterField = root.Element("BugFilterField").Value;
            document.BugFilterValue = root.Element("BugFilterValue").Value;
            document.PriorityRed = root.Element("PriorityRed").Value;

            IEnumerable<XElement> elements = root.Element("PropertyMappings").Elements();
            foreach (XElement element in elements)
            {
                document.PropertyMappingCollection[element.Name.ToString()] = element.Value;
            }

            return document;
        }
Example #25
0
        /* INPUT 1:
        ../../Faded.mp4
        ../../
        5
        INPUT 2:
        ../../text.txt
        ../../
        3

         * * * */
        private static void Slice(string sourceFile, string destinationDirectory, int parts)
        {
            FileStream reader = new FileStream(sourceFile, FileMode.Open);
            FileInfo file = new FileInfo(sourceFile);
            long chunkSize = (long)(file.Length/parts);
            BigInteger counter = -1;
            if (file.Length%2 == 1)
            {
                counter = 0;
            }
            int fileCounter = 1;
            int readBytesVariable = reader.ReadByte();
            List<byte> lsBytes = new List<byte>();
            lsBytes.Add((byte)readBytesVariable);
            while (readBytesVariable != -1)
            {

                if ((counter%chunkSize == 0 && counter != 0) || counter == file.Length)
                {
                    string fileName = destinationDirectory + "Part-" + fileCounter + "." + sourceFile.Split(new char[]{'.'},StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
                    FileStream writer = new FileStream(fileName, FileMode.Create,FileAccess.Write);
                    writer.Write(lsBytes.ToArray(), 0,lsBytes.Count);
                    writer.Flush();
                    writer.Dispose();
                    lsBytes.Clear();
                    fileCounter++;
                }

                readBytesVariable = reader.ReadByte();
                lsBytes.Add((byte)readBytesVariable);
                counter++;
            }
        }
        public static void ExtractNuGet(string path)
        {
            using (var stream = Assembly.GetExecutingAssembly()
                .GetManifestResourceStream("Protobuild.BuildResources.nuget.exe"))
            {
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, (int)stream.Length);
                using (var writer = new FileStream(Path.Combine(path, "nuget.exe"), FileMode.Create))
                {
                    writer.Write(bytes, 0, bytes.Length);
                    writer.Flush();
                }

                // Attempt to set the executable bit if possible.  On platforms
                // where this doesn't work, it doesn't matter anyway.
                try
                {
                    var p = Process.Start("chmod", "a+x " + Path.Combine(path, "nuget.exe").Replace("\\", "\\\\").Replace(" ", "\\ "));
                    p.WaitForExit();
                }
                catch (Exception)
                {
                }
            }
        }
Example #27
0
        public void GetTest()
        {
            var accessToken = AccessTokenContainer.GetToken(_appId);

            UploadTest();//上传

            using (MemoryStream ms = new MemoryStream())
            {
                Media.Get(accessToken, mediaId, ms);
                Assert.IsTrue(ms.Length > 0);

                //保存到文件
                var fileName = string.Format(@"E:\testpic_{0}.jpg", DateTime.Now.Ticks);
                using (FileStream fs = new FileStream(fileName, FileMode.Create))
                {
                    ms.Position = 0;
                    byte[] buffer = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        fs.Write(buffer, 0, bytesRead);
                    }
                    fs.Flush();
                }

                Assert.IsTrue(File.Exists(fileName));
            }
        }
Example #28
0
        public void CreateSeasonalTileInfo()
        {
            m_StaticCounts = new Dictionary<int, int>();

            TileMatrixData tileData = new TileMatrixData(0);

            Map map = new Map(0);

            for (uint y = 0; y < tileData.ChunkHeight; y++)
            {
                Tracer.Info("Map Parser: row {0}.", y);
                for (uint x = 0; x < tileData.ChunkWidth; x++)
                {
                    ParseMapBlock(tileData, x, y);
                }
            }

            var items = from pair in m_StaticCounts
                        orderby pair.Value descending
                        select pair;

            using (FileStream file = new FileStream(@"AllTiles.txt", FileMode.Create))
            {
                StreamWriter stream = new StreamWriter(file);
                foreach (KeyValuePair<int, int> pair in items)
                {
                    ItemData itemData = TileData.ItemData[pair.Key];
                    if ((itemData.IsBackground || itemData.IsFoliage) && !itemData.IsWet && !itemData.IsSurface)
                        stream.WriteLine(string.Format("{0},{1} ; {2}", pair.Key, pair.Value, itemData.Name));
                }
                stream.Flush();
                file.Flush();
            }
        }
Example #29
0
        /// <summary>
        /// 设置调试
        /// </summary>
        /// <param name="isDebug"></param>
        internal static void SetDebug(bool isDebug)
        {
            string content = String.Empty;
            bool isChange = false;

            using (StreamReader fs = new StreamReader(String.Format("{0}Web.config", AppDomain.CurrentDomain.BaseDirectory)))
            {
                content = fs.ReadToEnd();
                fs.Dispose();
            }

            Regex reg = new Regex("<compilation([^(debug)])+debug=\"([^\"]+)\"", RegexOptions.IgnoreCase);
            if (reg.IsMatch(content))
            {
                Match m = reg.Match(content);
                if ((m.Groups[2].Value == "true" && !isDebug) || (m.Groups[2].Value == "false" && isDebug))
                {
                    content = reg.Replace(content, String.Format("<compilation$1debug=\"{0}\"", isDebug ? "true" : "false"));
                    isChange = true;
                }
            }

            if (isChange)
            {
                using (FileStream fs = new FileStream(String.Format("{0}Web.config", AppDomain.CurrentDomain.BaseDirectory),
                    FileMode.Truncate, FileAccess.Write,FileShare.ReadWrite))
                {
                    byte[] data = Encoding.UTF8.GetBytes(content);
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                    fs.Dispose();
                }
            }
        }
Example #30
0
 public static bool CreateFile(string path,string fileName,byte[] bytes)
 {
     Stream stream = null;
     string fullPath = path + fileName;
     string dir = fullPath.Substring(0, fullPath.LastIndexOf("/"));
     bool isSuccess = false;
     try
     {
         DirectoryInfo dirInfo = new DirectoryInfo(dir);
         if (!dirInfo.Exists) dirInfo.Create();
         FileInfo fileInfo = new FileInfo(fullPath);
         stream = new FileStream(fileInfo.FullName, FileMode.OpenOrCreate, FileAccess.Write);
         stream.Write(bytes, 0, bytes.Length);
         stream.Flush();
         isSuccess = true;
     }
     catch(System.Exception ex)
     {
         Debug.Log("Create File ERROR:"+ex.Message);
     }
     finally
     {
         if(stream!=null)
         {
             stream.Close();
             stream.Dispose();
         }
     }
     return isSuccess;
 }