//Đư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(); } } }
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 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 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); } }
public NtStatus WriteFile(byte[] buffer, out int writtenBytes, long offset) { try { var(stream, streamFromCache) = GetStream(true); stream.Position = offset; writtenBytes = buffer.Length; stream.Write(buffer, 0, buffer.Length); stream.Flush(); file.Refresh(); FileInformation.Length = file.Length; if (!streamFromCache) { stream.Close(); } return(DokanResult.Success); } catch (FileNotFoundException e) { writtenBytes = 0; Console.WriteLine("DokanPBO::WriteFile failed due to FileNotFoundException: " + e); return(DokanResult.FileNotFound); } //#TODO access denied exception }
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)); } }
internal void WriteLogFile(string message) { if (logFile != null && logFile.CanWrite == true) { //check if we need to make a new log file for a new day if (DateTime.Now.Day != lastDayWritten && FormMain.Instance.IceChatOptions.SeperateLogs) { logFile.Close(); logFile.Dispose(); if (_consoleTab != null) { CreateConsoleLog(); } else if (_tabPage != null) { CreateStandardLog(); } } //Check if log format has changed else if (((FormMain.Instance.IceChatOptions.LogFormat == "Plain Text" || FormMain.Instance.IceChatOptions.LogFormat == "Colored Text") && fileExtension == ".html") || (FormMain.Instance.IceChatOptions.LogFormat == "HTML" && fileExtension == ".log")) { logFile.Close(); logFile.Dispose(); if (_consoleTab != null) { CreateConsoleLog(); } else if (_tabPage != null) { CreateStandardLog(); } } if (FormMain.Instance.IceChatOptions.LogFormat == "Plain Text") { //System.Diagnostics.Debug.WriteLine("1:"+message); message = StripCodes(message); //System.Diagnostics.Debug.WriteLine("2:"+message); message += "\r\n"; logFile.Write(System.Text.Encoding.UTF8.GetBytes(message), 0, System.Text.Encoding.UTF8.GetBytes(message).Length); } else if (FormMain.Instance.IceChatOptions.LogFormat == "Colored Text") { message += "\r\n"; logFile.Write(System.Text.Encoding.UTF8.GetBytes(message), 0, System.Text.Encoding.UTF8.GetBytes(message).Length); } else if (FormMain.Instance.IceChatOptions.LogFormat == "HTML") { message = ReplaceColorCodes(message); logFile.Write(System.Text.Encoding.UTF8.GetBytes(message), 0, System.Text.Encoding.UTF8.GetBytes(message).Length); } logFile.Flush(); } }
public override void Flush() { if (_m_disposed) { throw ADP.ObjectDisposed(this); } _m_fs.Flush(); }
public bool Commit() { if (LF.Length == 0) { return(false); } LF.Flush(true); return(true); }
public void Write(string buffer) { if (_file == null || !_file.CanWrite) { return; } _file.Write(Encoding.UTF8.GetBytes(buffer)); _file.Flush(); }
public void BasicFlushFunctionality() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.WriteByte(0); fs.Flush(false); fs.WriteByte(0xFF); fs.Flush(true); } }
static void WriteBinaryFile(string FileName, byte[] bytes, FileMode mode) { string path = System.IO.Path.GetDirectoryName(FileName); System.IO.Directory.CreateDirectory(path); System.IO.FileStream fs = new System.IO.FileStream(FileName, mode); fs.Flush(); fs.Write(bytes, 0, bytes.Length); fs.Flush(); fs.Close(); }
private void SplitByBookmark(iTextSharp.text.pdf.PdfReader reader, int pageFrom, int PageTo, string outPutName, string inPutFileName, string subdirectory) { Document document = new Document(); FileStream fs = new System.IO.FileStream(System.IO.Path.GetDirectoryName(inPutFileName) + '\\' + subdirectory + '\\' + outPutName, System.IO.FileMode.Create); try { PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); PdfContentByte cb = writer.DirectContent; //holds pdf data PdfImportedPage page; if (pageFrom == PageTo && pageFrom == 1) { document.NewPage(); page = writer.GetImportedPage(reader, pageFrom); cb.AddTemplate(page, 0, 0); pageFrom++; fs.Flush(); document.Close(); fs.Close(); } else { while (pageFrom <= PageTo) { document.NewPage(); page = writer.GetImportedPage(reader, pageFrom); cb.AddTemplate(page, 0, 0); pageFrom++; fs.Flush(); //document.Close(); //fs.Close(); } } } catch (Exception ex) { throw ex; } finally { if (document.IsOpen()) { document.Close(); } if (fs != null) { fs.Close(); } } }
/// <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 = ""; } }
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); } }
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(); } }
public static void Compress(string FileToCompress, string CompressedFile) { byte[] buffer = new byte[1024 * 1024]; // 1MB using (System.IO.FileStream sourceFile = System.IO.File.OpenRead(FileToCompress)) { using (System.IO.FileStream destinationFile = System.IO.File.Create(CompressedFile)) { using (System.IO.Compression.GZipStream output = new System.IO.Compression.GZipStream(destinationFile, System.IO.Compression.CompressionMode.Compress)) { int bytesRead = 0; while (bytesRead < sourceFile.Length) { int ReadLength = sourceFile.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, ReadLength); output.Flush(); bytesRead += ReadLength; } // Whend destinationFile.Flush(); } // End Using System.IO.Compression.GZipStream output destinationFile.Close(); } // End Using System.IO.FileStream destinationFile // Close the files. sourceFile.Close(); } // End Using System.IO.FileStream sourceFile } // End Sub CompressFile
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) { } } }
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; }
//生成一个文件 public static bool CreateFile(string filecontent, string path) { try { string filePath = System.Web.HttpContext.Current.Server.MapPath(path); if (File.Exists(filePath)) { File.Delete(filePath); } else { System.IO.FileStream fs = System.IO.File.Create(path); byte[] byContent = System.Text.Encoding.GetEncoding("gb2312").GetBytes(filecontent); fs.Write(byContent, 0, byContent.Length); fs.Flush(); fs.Close(); } return(true); } catch (Exception ex) { return(false); } finally { } }
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); }
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); } }
/// <summary> /// Write the specified collection of statistics to the XML /// statistics file, creating it if it does not already exist /// </summary> /// <param name="stats">The collection of statistics.</param> /// <param name="integrationResult">The build for which the /// statistics were collected.</param> /// <remarks> /// The XML document takes the following form: /// <statistics> /// <integration build-label="label" status="status" /// day="day_of_month" month="month_name" year="year"> /// <statistic name="name"> /// value /// </statistic> /// </integration> /// </statistics> /// </remarks> private static void UpdateXmlFile(IEnumerable <StatisticResult> stats, IIntegrationResult integrationResult) { Directory.CreateDirectory(integrationResult.ArtifactDirectory); // make an xml element of the current integration System.Text.StringBuilder integration = new System.Text.StringBuilder(); DateTime now = DateTime.Now; integration.AppendFormat("<integration build-label=\"{0}\" status=\"{1}\" day=\"{2}\" month=\"{3}\" year=\"{4}\">", integrationResult.Label, integrationResult.Status.ToString(), now.Day.ToString(CultureInfo.CurrentCulture), now.ToString("MMM", CultureInfo.InvariantCulture), now.Year.ToString(CultureInfo.CurrentCulture)); integration.AppendLine(ToXml(stats)); integration.Append("</integration>"); // append to the statistics file string lastFile = XmlStatisticsFile(integrationResult); System.IO.FileStream fs = new System.IO.FileStream(lastFile, System.IO.FileMode.Append); fs.Seek(0, System.IO.SeekOrigin.End); System.IO.StreamWriter sw = new System.IO.StreamWriter(fs); sw.WriteLine(integration.ToString()); sw.Flush(); fs.Flush(); sw.Close(); fs.Close(); }
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; } }
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; }
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(); } }
// Writes zeros to a file stream, with space advantage on compressed and sparse files. public static void WriteZeros(System.IO.FileStream fs, long begin, long end) { #if NETSTANDARD2_0 if (fs.Length < end) { fs.SetLength(end); // Just extend the length of the file } #else // Hopefully this works as expected, it's hard to get this working right over the .NET framework fs.Flush(); // So that ALL of the buffers are cleared and written to the file. zeroinfo zi = new zeroinfo(); int retd; // Get the file handle IntPtr hndl = fs.SafeFileHandle.DangerousGetHandle(); if (end > fs.Length) { while (end > fs.Length) { long pos = fs.Length; long write = Math.Min(0x100000, end - pos); fs.SetLength(pos + write); zi.begin = pos; zi.end = pos + write; SetZeroData(hndl, FSCTL_SET_ZERO_DATA, ref zi, 16, IntPtr.Zero, 0, out retd, IntPtr.Zero); } } zi.begin = begin; zi.end = end; SetZeroData(hndl, FSCTL_SET_ZERO_DATA, ref zi, 16, IntPtr.Zero, 0, out retd, IntPtr.Zero); fs.Position = end; #endif }
/// <summary> /// Nguyen Thai Binh /// Dung de load keymessage cua form login va connect khi chua co chuoi ket noi -> chua connect duoc database /// </summary> /// <param name="DirectoryPath"></param> /// <param name="LangID"></param> /// <param name="PageName"></param> /// <returns></returns> public static DataSet GetDataSet_Keysearch_Client(string DirectoryPath, Int16 LangID, string PageName) { DataSet ds = null; string CacheName = String.Format("{0}-{1}", PageName, LangID.ToString()); string FilePath = DirectoryPath + String.Format("\\{0}.xml", CacheName); if (File.Exists(FilePath)) { ds = new DataSet(); System.IO.FileStream fsReadXml = new System.IO.FileStream(FilePath, System.IO.FileMode.Open); ds.ReadXml(fsReadXml); fsReadXml.Flush(); fsReadXml.Dispose(); } else { ds = PAGEDAO.getAllMessagerInPage(PageName, LangID); if (!File.Exists(DirectoryPath)) { System.IO.Directory.CreateDirectory(DirectoryPath); } if (!System.IO.File.Exists(FilePath)) { using (System.IO.FileStream stream = System.IO.File.Create(FilePath, 1024)) ds.WriteXml(stream); } } return(ds); }
//向文件中增加内容 public static bool UpdateFile(string filecontent, string path) { try { string filePath = System.Web.HttpContext.Current.Server.MapPath(path); if (!File.Exists(filePath)) { System.IO.FileStream fs = System.IO.File.Create(filePath); byte[] byContent = System.Text.Encoding.GetEncoding("gb2312").GetBytes(filecontent); fs.Write(byContent, 0, byContent.Length); fs.Flush(); fs.Close(); } System.IO.FileStream files = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.ReadWrite); StreamReader sReader = new StreamReader(files, System.Text.Encoding.Default); string oldstr = sReader.ReadToEnd(); oldstr += filecontent; //把新的内容重新写入 StreamWriter sWriter = new StreamWriter(files, System.Text.Encoding.Default); sWriter.Write(oldstr); sWriter.Flush(); sWriter.Close(); sReader.Close(); files.Close(); return(true); } catch (Exception ex) { return(false); } }
private void Link() { try { Ret = null; MyConfig.TopSlopeMultiplier = Convert.ToDouble(TopSlopeMultiplier.Text); MyConfig.BottomSlopeMultiplier = Convert.ToDouble(BottomSlopeMultiplier.Text); MyConfig.TopSlopeDX = Convert.ToDouble(TopSlopeDX.Text); MyConfig.BottomSlopeDX = Convert.ToDouble(BottomSlopeDX.Text); MyConfig.TopSlopeDY = Convert.ToDouble(TopSlopeDY.Text); MyConfig.BottomSlopeDY = Convert.ToDouble(BottomSlopeDY.Text); if (ifl == null || imng == null) { LoadAssemblyModule(); } System.IO.FileStream f = new System.IO.FileStream(CatalogFile.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read); Catalog Cat = new Catalog(f); f.Close(); Ret = ifl.Link(Cat, CHORUSFormat.Checked ? typeof(SySal.Scanning.Plate.IO.CHORUS.LinkedZone) : typeof(SySal.Scanning.Plate.IO.OPERA.LinkedZone)); System.IO.FileStream o = new System.IO.FileStream(OutputFile.Text, System.IO.FileMode.Create); Ret.Save(o); o.Flush(); o.Close(); } catch (Exception x) { System.Windows.Forms.MessageBox.Show(x.ToString(), x.Message); } }
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; }
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 }); }
/* 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 void WriteFrame(PcapPacket frame, bool flush) { lock (this) { TimeSpan delta = frame.Timestamp.Subtract(this.referenceTime); //The smallest unit of time is the tick, which is equal to 100 nanoseconds. A tick can be negative or positive. long totalMicroseconds = delta.Ticks / 10; uint seconds = (uint)(totalMicroseconds / 1000000); uint microseconds = (uint)(totalMicroseconds % 1000000); byte[] headerData = ToByteArray(frame.Header); fileStream.Write(ToByteArray(seconds), 0, 4); fileStream.Write(ToByteArray(microseconds), 0, 4); //number of octets of packet saved in file fileStream.Write(ToByteArray((uint)frame.Data.Length + headerData.Length), 0, 4); //actual length of packet fileStream.Write(ToByteArray((uint)frame.Data.Length + headerData.Length), 0, 4); //data fileStream.Write(headerData, 0, headerData.Length); fileStream.Write(frame.Data, 0, frame.Data.Length); if (flush) { fileStream.Flush(); } } }
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)); } }
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; }
private void tsbViewAttachments_Click(object sender, EventArgs e) { if (dgList.SelectedRows.Count == 0) { return; } int id = Convert.ToInt32(dgList.SelectedRows[0].Cells["id"].Value); var result = da.GetMemberAttachment(id); SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.Title = "Save"; saveDialog.Filter = "Excel Files (*.xls;*.xlsx)|*.xls;*.xlsx" + "|" + "Word Files(*.dox;*.docx)|*.dox;*.docx" + "|" + "PDF Files(*.pdf;)|*.pdf;" + "|" + "Image Files (*.png;*.jpg)|*.png;*.jpg"; saveDialog.FileName = result.FileName; if (saveDialog.ShowDialog() == DialogResult.OK) { string filename = saveDialog.FileName; System.IO.FileStream fs = new System.IO.FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Write); fs.Write(result.FileContents, 0, result.FileContents.Length); fs.Flush(); fs.Close(); } }
//写备份文件 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; } }
public string Read(string filePath) { if (!System.IO.File.Exists(filePath)) { throw new Exception("文件不存在"); } StringBuilder result = new StringBuilder(); using (System.IO.FileStream file = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, 8, System.IO.FileOptions.Asynchronous)) { byte[] buffer = new byte[file.Length]; file.Seek(0, System.IO.SeekOrigin.Begin); file.Read(buffer, 0, buffer.Length); System.IO.MemoryStream stream = new System.IO.MemoryStream(); stream.Write(buffer, 0, buffer.Length); var content = System.Text.Encoding.UTF8.GetString(stream.ToArray()); result.Append(content); stream.Flush(); stream.Dispose(); stream.Close(); file.Flush(); file.Close(); } return(result.ToString()); }
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); } }
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; }
/// <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(); } } }
/// <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(); } }
static void CheckExml(string path) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(path); var xmlNodes = doc.ChildNodes[1].ChildNodes; List <ExmlError> error = new List <ExmlError>(); foreach (XmlNode node in xmlNodes) { CheckXmlNode(node, error, path); } if (error.Count > 0) { string logfile = GetLogPath() + "/error.log"; using (System.IO.FileStream fs = System.IO.File.Open(logfile, System.IO.FileMode.OpenOrCreate)) { foreach (var item in error) { byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes("tu pian bu chunzi :" + item.errorSource + "(" + item.path + ")\r\n"); fs.Write(bytes, 0, bytes.Length); } fs.Flush(); fs.Close(); } } }
/// <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(); }
void bdsEmployee_PositionChanged(object sender, EventArgs e) { drCurrent = ((DataRowView)bdsEmployee.Current).Row; bdsHopDong.Filter = "Ma_CbNv = '" + drCurrent["Ma_CbNv"] + "'"; bdsHopDongPL.Filter = "Ma_CbNv = '" + drCurrent["Ma_CbNv"] + "'"; object objPic = SQLExec.ExecuteReturnValue("SELECT Hinh FROM LINHANVIEN WHERE Ma_CbNv = '" + (string)drCurrent["Ma_CbNv"] + "'"); Byte[] bytePic = (Byte[])objPic; if (objPic != null && objPic != DBNull.Value && bytePic.Length != 0) { byte[] barrImg = bytePic; string strFileName = Convert.ToString(DateTime.Now.ToFileTime()); System.IO.FileStream fs = new System.IO.FileStream(strFileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write); fs.Write(barrImg, 0, barrImg.Length); fs.Flush(); fs.Close(); picHinh.Image = Image.FromFile(strFileName); picHinh.SizeMode = PictureBoxSizeMode.Zoom; } else { picHinh.Image = null; } }
public string GetDataBasePath(string fileName) { string documetsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var path = Path.Combine(documetsPath, fileName); // Копирование файла бд из папки Assets по пути path на устройство //if (!File.Exists(path)) //{ Context context = Android.App.Application.Context; var dbAssetStream = context.Assets.Open(fileName); var dbFileStream = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate); var buffer = new byte[1024]; int bufLength = buffer.Length; int readedLength; while ((readedLength = dbAssetStream.Read(buffer, 0, bufLength)) > 0) { dbFileStream.Write(buffer, 0, readedLength); } dbFileStream.Flush(); dbFileStream.Close(); dbAssetStream.Close(); //} return(path); }
static SequenceParameter() { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SequenceData"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string filename = Path.Combine(path, "sequence.data"); if (!File.Exists(filename)) { mFileStream = File.Open(filename, FileMode.OpenOrCreate); byte[] data = new byte[mRecordSize * mRecordCount]; mFileStream.Write(data, 0, mRecordSize * mRecordCount); mFileStream.Flush(); mFileStream.Close(); } mSequenceFile = MemoryMappedFile.CreateFromFile(filename); mAccessor = mSequenceFile.CreateViewAccessor(mRecordSize, 0, MemoryMappedFileAccess.ReadWrite); mSequenceItems = new Dictionary <string, SequenceItem>(); Load(); }
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); }
///// <summary> ///// Returns a list of files in a give directory. ///// </summary> ///// <param name="fullName">The full path name to the directory.</param> ///// <param name="indexFileNameFilter"></param> ///// <returns>An array containing the files.</returns> //public static System.String[] GetLuceneIndexFiles(System.String fullName, // Index.IndexFileNameFilter indexFileNameFilter) //{ // System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(fullName); // System.Collections.ArrayList list = new System.Collections.ArrayList(); // foreach (System.IO.FileInfo fInfo in dInfo.GetFiles()) // { // if (indexFileNameFilter.Accept(fInfo, fInfo.Name) == true) // { // list.Add(fInfo.Name); // } // } // System.String[] retFiles = new System.String[list.Count]; // list.CopyTo(retFiles); // return retFiles; //} // Disable the obsolete warning since we must use FileStream.Handle // because Mono does not support FileSystem.SafeFileHandle at present. #pragma warning disable 618 /// <summary> /// Flushes the specified file stream. Ensures that all buffered /// data is actually written to the file system. /// </summary> /// <param name="fileStream">The file stream.</param> public static void Sync(System.IO.FileStream fileStream) { if (fileStream == null) { throw new ArgumentNullException("fileStream"); } fileStream.Flush(true); if (OS.IsWindows) { if (!FlushFileBuffers(fileStream.Handle)) { throw new IOException(); } } //else if (OS.IsUnix) //{ // if (fsync(fileStream.Handle) != IntPtr.Zero) // throw new System.IO.IOException(); //} //else //{ // throw new NotImplementedException(); //} }
public string GetDatabasePath(string sqliteFilename) { string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var path = Path.Combine(documentsPath, sqliteFilename); if (!File.Exists(path)) { Context context = Android.App.Application.Context; var dbAssetStream = context.Assets.Open(sqliteFilename); var dbFileStream = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate); var buffer = new byte[1024]; int b = buffer.Length; int length; while ((length = dbAssetStream.Read(buffer, 0, b)) > 0) { dbFileStream.Write(buffer, 0, length); } dbFileStream.Flush(); dbFileStream.Close(); dbAssetStream.Close(); } return(path); }
private void WriteFile(String filename, String content) { System.IO.FileStream f = null; StreamWriter writer = null; try { if (!System.IO.File.Exists(filename)) { f = System.IO.File.Create(filename); f.Flush(); f.Close(); } writer = new StreamWriter(filename); writer.WriteLine(content); writer.Flush(); writer.Close(); } catch (Exception e) { } finally { if (f != null) { f.Close(); } if (writer != null) { writer.Close(); } } }
private void Save() { System.IO.FileStream file = null; try { lock (sentry) { file = new System.IO.FileStream(path, System.IO.FileMode.Create); System.Runtime.Serialization.Formatters.Soap.SoapFormatter formatter = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter(); formatter.Serialize(file, settings); } } catch { } finally { if (file != null) { file.Flush(); file.Dispose(); file = null; } } }
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; }
///// <summary> ///// Returns a list of files in a give directory. ///// </summary> ///// <param name="fullName">The full path name to the directory.</param> ///// <param name="indexFileNameFilter"></param> ///// <returns>An array containing the files.</returns> //public static System.String[] GetLuceneIndexFiles(System.String fullName, // Index.IndexFileNameFilter indexFileNameFilter) //{ // System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(fullName); // System.Collections.ArrayList list = new System.Collections.ArrayList(); // foreach (System.IO.FileInfo fInfo in dInfo.GetFiles()) // { // if (indexFileNameFilter.Accept(fInfo, fInfo.Name) == true) // { // list.Add(fInfo.Name); // } // } // System.String[] retFiles = new System.String[list.Count]; // list.CopyTo(retFiles); // return retFiles; //} // Disable the obsolete warning since we must use FileStream.Handle // because Mono does not support FileSystem.SafeFileHandle at present. #pragma warning disable 618 /// <summary> /// Flushes the specified file stream. Ensures that all buffered /// data is actually written to the file system. /// </summary> /// <param name="fileStream">The file stream.</param> public static void Sync(System.IO.FileStream fileStream) { if (fileStream == null) { throw new ArgumentNullException("fileStream"); } fileStream.Flush(true); if (OS.IsWindows) { #if NETSTANDARD // Getting the SafeFileHandle property automatically flushes the // stream: https://msdn.microsoft.com/en-us/library/system.io.filestream.safefilehandle(v=vs.110).aspx var handle = fileStream.SafeFileHandle; #else if (!FlushFileBuffers(fileStream.Handle)) { throw new IOException(); } #endif } //else if (OS.IsUnix) //{ // if (fsync(fileStream.Handle) != IntPtr.Zero) // throw new System.IO.IOException(); //} //else //{ // throw new NotImplementedException(); //} }
/// <summary> /// 追加一条日志信息 /// </summary> /// <param name="text"></param> public static void Append(string text) { try { text += "\r\n"; string fileName = GetPath("1"); // "1"获取当前时间路径 string fileNameLast = GetPath("2"); // "2"获取3天前得路径 if (!System.IO.Directory.Exists(fileName)) { System.IO.Directory.CreateDirectory(fileName); } if (File.Exists(fileNameLast)) { File.Delete(fileNameLast); } using (System.IO.FileStream s = new System.IO.FileStream(fileName + DateTime.Now.ToString("yyyy-MM-dd-HH") + ".txt", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite, 8, System.IO.FileOptions.Asynchronous)) { s.Write(System.Text.Encoding.GetEncoding("GB2312").GetBytes(text), 0, System.Text.Encoding.GetEncoding("GB2312").GetBytes(text).Length); s.Flush(); } } catch (Exception ex) { } }
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 static bool WriteFile(byte[] byData, string path) { try { string filepath = System.Web.HttpContext.Current.Server.MapPath(path); if (File.Exists(path)) { File.Delete(path); } System.IO.FileStream fs = System.IO.File.Create(path); fs.Write(byData, 0, byData.Length); fs.Flush(); fs.Close(); return(true); } catch (Exception ex) { return(false); } finally { } }
public static LuaByteBuffer unserialMessageInfo(string path, int offset) { if (System.IO.File.Exists(path)) { using (System.IO.FileStream fs = System.IO.File.OpenRead(path)) { if (fs.Length <= offset) { return(null); } if (offset > 0) { fs.Seek(offset, System.IO.SeekOrigin.Begin); } byte[] bytes = new byte[4]; fs.Read(bytes, 0, 4); int length = readInt32Byte(bytes); bytes = new byte[length]; fs.Read(bytes, 0, length); fs.Flush(); return(new LuaByteBuffer(bytes)); } } return(null); }
void Encoding() { if (EncodingData == null || string.IsNullOrEmpty(SavePath)) { Debug.LogError("Encoding Data Error"); return; } DracoMeshLoader dracoLoader = new DracoMeshLoader(); byte[] dracoData = dracoLoader.EncodeUnityMesh(EncodingData); try { if (dracoData != null && dracoData.Length > 0) { using (System.IO.FileStream saveFile = System.IO.File.Open(SavePath, System.IO.FileMode.Create)) { saveFile.Write(dracoData, 0, dracoData.Length); saveFile.Flush(); } } Debug.Log("Encode Finish"); return; } catch (System.Exception e) { Debug.LogError(e.ToString()); } Debug.LogError("Encode Faile"); }