/// <summary> /// Запись в ЛОГ-файл /// </summary> /// <param name="str"></param> public void WriteToLog(string str, bool doWrite = true) { if (doWrite) { StreamWriter sw = null; FileStream fs = null; try { string curDir = AppDomain.CurrentDomain.BaseDirectory; fs = new FileStream(curDir + "teplouchetlog.pi", FileMode.Append, FileAccess.Write, FileShare.ReadWrite); sw = new StreamWriter(fs, Encoding.Default); if (m_vport == null) sw.WriteLine(DateTime.Now.ToString() + ": Unknown port: adress: " + m_address + ": " + str); else sw.WriteLine(DateTime.Now.ToString() + ": " + m_vport.GetName() + ": adress: " + m_address + ": " + str); sw.Close(); fs.Close(); } catch { } finally { if (sw != null) { sw.Close(); sw = null; } if (fs != null) { fs.Close(); fs = null; } } } }
private void compressFile(string source_file, string destination_file) { FileStream original_file = new FileStream(source_file, FileMode.Open, FileAccess.Read, FileShare.Read); byte[] buffer = new byte[original_file.Length]; // Make sure the file can be read first. int count = original_file.Read(buffer, 0, buffer.Length); if(count != buffer.Length) { original_file.Close(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error: Could not open " + source_file +"For reading."); Console.ResetColor(); return; } original_file.Close(); Stream out_stream = File.Create(destination_file); GZipStream gZip = new GZipStream(out_stream, CompressionMode.Compress, true); gZip.Write(buffer, 0, buffer.Length); gZip.Close(); Console.WriteLine("Original size: {0}, Compressed size: {1}", buffer.Length, out_stream.Length); out_stream.Close(); }
public static bool load() { //---------------------------------输出数据库--------------------------- if (!(File.Exists(strDatabasePath))) { string dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\ContorlSetting\\"; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); FileStream fs = new FileStream(strDatabasePath, FileMode.OpenOrCreate, FileAccess.Write); try { Byte[] b = SAS.Properties.Resources.DataBase; fs.Write(b, 0, b.Length); if (fs != null) fs.Close(); } catch { if (fs != null) fs.Close(); return false; } } // -----------------------------第一次加载代码,------------------------------ //if (conn.State != ConnectionState.Open) // conn.Open(); ////-----------------------------操作完成后记得关闭连接------------------------------ //conn.Close(); return true; }
public static void UnZip(this FileInfo fileInfo, string destiantionFolder) { using (var fileStreamIn = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read)) { using (var zipInStream = new ZipInputStream(fileStreamIn)) { var entry = zipInStream.GetNextEntry(); FileStream fileStreamOut = null; while (entry != null) { fileStreamOut = new FileStream(destiantionFolder + @"\" + entry.Name, FileMode.Create, FileAccess.Write); int size; byte[] buffer = new byte[4096]; do { size = zipInStream.Read(buffer, 0, buffer.Length); fileStreamOut.Write(buffer, 0, size); } while (size > 0); fileStreamOut.Close(); entry = zipInStream.GetNextEntry(); } if (fileStreamOut != null) fileStreamOut.Close(); zipInStream.Close(); } fileStreamIn.Close(); } }
public static bool Compare(string file1, string file2) { if (file1.Equals(file2)) return true; if (!File.Exists(file1) || !File.Exists(file2)) return false; FileStream first = new FileStream(file1, FileMode.Open); FileStream second = new FileStream(file2, FileMode.Open); if (first.Length != second.Length) { first.Close(); second.Close(); return false; } int byte1; int byte2; do { byte1 = first.ReadByte(); byte2 = second.ReadByte(); } while ((byte1 == byte2) && (byte1 != -1)); first.Close(); second.Close(); return (byte1 == byte2); }
public static bool SaveSettingsFile(PluginSettingsBase settings, Type type, string filename) { MemoryStream ms = null; FileStream fs = null; XmlSerializer xs = null; try { ms = new MemoryStream(); fs = new FileStream(filename, FileMode.Create, FileAccess.Write); xs = new XmlSerializer(type); xs.Serialize(ms, settings); ms.Seek(0, SeekOrigin.Begin); fs.Write(ms.ToArray(), 0, (int)ms.Length); ms.Close(); fs.Close(); return true; } catch (Exception) { return false; } finally { if (ms != null) ms.Close(); if (fs != null) fs.Close(); } }
/// <summary> /// 根据path反序列xml /// </summary> /// <param name="path">文件路径</param> /// <returns>返回ObjConfig的对象</returns> public static ObjConfig Get(string path) { if (_objConfig == null) { FileStream fs = null; try { XmlSerializer xs = new XmlSerializer(typeof(ObjConfig)); fs = new FileStream(path, FileMode.Open, FileAccess.Read); _objConfig = (ObjConfig)xs.Deserialize(fs); fs.Close(); return _objConfig; } catch(Exception ex) { if (fs != null) fs.Close(); throw ex; } } else { return _objConfig; } }
private static void CopyAsync(byte[] buffer, FileStream inputStream, Stream outputStream, TaskCompletionSource<object> tcs) { inputStream.ReadAsync(buffer).Then(read => { if (read > 0) { outputStream.WriteAsync(buffer, 0, read) .Then(() => CopyAsync(buffer, inputStream, outputStream, tcs)) .Catch(ex => { inputStream.Close(); outputStream.Close(); tcs.SetException(ex); }); } else { inputStream.Close(); outputStream.Close(); tcs.SetResult(null); } }) .Catch(ex => { inputStream.Close(); outputStream.Close(); tcs.SetException(ex); }); }
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 { } }
private static long _indexcount;//索引个数 static IpHelper() { string filePath = Common.GetMapPath("/App_Data/Site/ipdata.config"); if (File.Exists(filePath)) { try { _ipdatefile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch { _ipdatefile.Close(); _ipdatefile.Dispose(); return; } _ipdatefile.Position = 0; _indexareabegin = ReadByte4(); _indexareaend = ReadByte4(); _indexcount = (_indexareaend - _indexareabegin) / LENGTH + 1; if (_indexcount > 0) { _state = true; } else { _ipdatefile.Close(); _ipdatefile.Dispose(); } } }
public void WriteFiles(string content) { try { FileStream fi = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "\\cache.txt", FileMode.Append); StreamWriter sw = new StreamWriter(fi, Encoding.UTF8); sw.WriteLine(content); sw.WriteLine("-------------------------------------------------------"); if (fi.Length >= (1024 * 1024 * 5)) { sw.Close(); fi.Close(); if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\cache.txt")) { File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\cache.txt"); } return; } sw.Close(); fi.Close(); } catch (Exception ex) { } }
public SymScope GetUnit(string FileName) { try { root_scope = unit_cache[FileName] as SymScope; if (root_scope != null) return root_scope; unit_name = System.IO.Path.GetFileNameWithoutExtension(FileName); this.readDebugInfo = true; this.FileName = FileName; if (!File.Exists(FileName)) return null; dir = System.IO.Path.GetDirectoryName(FileName); fs = new FileStream(FileName, FileMode.Open, FileAccess.Read); br = new BinaryReader(fs); ReadPCUHeader(); root_scope = new InterfaceUnitScope(new SymInfo(unit_name, SymbolKind.Namespace,unit_name),null); unit_cache[FileName] = root_scope; cur_scope = root_scope; AddReferencedAssemblies(); ReadInterfacePart(); fs.Close(); } catch (Exception e) { fs.Close(); return root_scope; } return root_scope; }
public static bool FileCompare(string file1, string file2) { int file1byte; int file2byte; FileStream fs1; FileStream fs2; if (file1 == file2) { return true; } fs1 = new FileStream(file1, FileMode.Open); fs2 = new FileStream(file2, FileMode.Open); if (fs1.Length != fs2.Length) { fs1.Close(); fs2.Close(); return false; } do { // Read one byte from each file. file1byte = fs1.ReadByte(); file2byte = fs2.ReadByte(); } while ((file1byte == file2byte) && (file1byte != -1)); fs1.Close(); fs2.Close(); // Return the success of the comparison. "file1byte" is // equal to "file2byte" at this point only if the files are // the same. return ((file1byte - file2byte) == 0); }
private static void DisplayContent(HttpWebResponse response, string id) { Stream stream = response.GetResponseStream(); if (stream != null) { string filePath = "D:\\pic\\" + id + ".png"; FileStream fs = new FileStream(filePath, FileMode.Create); GZipStream gzip = new GZipStream(stream, CompressionMode.Decompress); byte[] bytes = new byte[1024]; int len; if ((len = gzip.Read(bytes, 0, bytes.Length)) > 0) { fs.Write(bytes, 0, len); } else { fs.Close(); File.Delete(filePath); throw new Exception(); } while ((len = gzip.Read(bytes, 0, bytes.Length)) > 0) { fs.Write(bytes, 0, len); } fs.Close(); } }
public bool PutImageToCache(MemoryStream tile, MapType type, Point pos, int zoom) { FileStream fs = null; try { string fileName = GetFilename(type, pos, zoom, true); fs = new FileStream(fileName, FileMode.Create); tile.WriteTo(fs); tile.Flush(); fs.Close(); fs.Dispose(); tile.Seek(0, SeekOrigin.Begin); return true; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Error in FilePureImageCache.PutImageToCache:\r\n" + ex.ToString()); if (fs != null) { fs.Close(); fs.Dispose(); } return false; } }
/// <summary> /// 将词库写入一个二进制文件,然后返回二进制文件的路径 /// </summary> /// <param name="wlList"></param> /// <returns></returns> public string Export(WordLibraryList wlList) { TouchPalChar rootChar = BuildTree(wlList); int endPositon = InitTreeNodePosition(rootChar, 4); //创建一个临时文件 string tempPath = Application.StartupPath + "\\temp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bak"; var fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(BitConverter.GetBytes(endPositon), 0, 4); WriteBinaryTree(rootChar, fs); fs.Close(); //int totalLength = 30; //foreach (WordLibrary wl in wlList) //{ // totalLength += wl.Word.Length * 28 + 5; //} //fs.Write(BitConverter.GetBytes(totalLength), 0, 4); //byte[] head = new byte[] { 0, 0, 0, 0, 0, 0, 0x1E, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //fs.Write(head, 0, 26); //int from = 4; //GlobalCache.JumpChar = new TouchPalChar() {BeginPosition = 4}; //for (int i = 0; i < wlList.Count; i++) //{ // WordLibrary wl = wlList[i]; // from = WriteWord(fs, wl, i == wlList.Count - 1); //} fs.Close(); return tempPath; }
public static object loadTestFile(string path, Type desiredType, bool failOnException = true, SerializationBinder customBinder = null) { Assert.IsTrue(System.IO.File.Exists(path), "Test file " + path + " does not exist."); BinaryFormatter b = new BinaryFormatter(); object loaded = null; FileStream fs = null; try { fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None); if (customBinder != null) b.Binder = customBinder; loaded = b.Deserialize(fs); fs.Close(); } catch (Exception e) { fs.Close(); if (failOnException) Assert.Fail("Caught exception when loading test file: " + e.Message); else throw; } Assert.IsNotNull(loaded, "Test file " + path + " loaded a null object."); Assert.IsInstanceOfType(loaded, desiredType, "Test file " + path + " did not resolve to desired type."); return loaded; }
public static void EditFile(int curLine, string newLineValue, string patch) { FileStream fs = new FileStream(patch, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8")); string line = sr.ReadLine(); StringBuilder sb = new StringBuilder(); if (curLine == 1) { line = newLineValue; sb.Append(line + "\r\n"); } else { for (int i = 1; line != null; i++) { sb.Append(line + "\r\n"); if (i != curLine - 1) line = sr.ReadLine(); else { sr.ReadLine(); line = newLineValue; } } } sr.Close(); fs.Close(); FileStream fs1 = new FileStream(patch, FileMode.Open, FileAccess.Write); StreamWriter sw = new StreamWriter(fs1); sw.Write(sb.ToString()); sw.Close(); fs.Close(); }
public static bool Activate() { FileStream fs = new FileStream("license.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); try { StreamReader sr = new StreamReader(fs); string a = sr.ReadLine(); string b = sr.ReadLine(); a = CryptorEngine.Decrypt(a); b = CryptorEngine.Decrypt(b); sr.Close(); fs.Close(); string[] tabs = a.Split('\n'); Statics.ValidTabletsIdList = new List<string>(); for (int i = 0; i < tabs.Length; i++) Statics.ValidTabletsIdList.Add(tabs[i]); if (b == Statics.HardwareId) return true; else return false; } catch { fs.Close(); return false; } }
public static bool FindString(FileInfo file, string str) { string currentStr; FileStream fin = null; StreamReader reader = null; try { fin = new FileStream(file.DirectoryName + "\\" + file.Name, FileMode.Open); reader = new StreamReader(fin); while ((currentStr = reader.ReadLine()) != null) { if (currentStr.Contains(str)) return true; } } catch (IOException ex) { Console.WriteLine(ex.Message); } finally { if (fin != null) fin.Close(); if (reader != null) fin.Close(); } return false; }
private void main() { // Nome arquivo de saida. Mude para o valor que quiser FileStream arquivo1Pdf = new FileStream(@"D:\Temp\teste1.pdf", FileMode.OpenOrCreate, FileAccess.Write); ControladorPDF.Instancia.obterProgramacaoPDF(new DateTime(2010, 06, 28), TipoProgramacao.DiaDaSemana, arquivo1Pdf); //arquivo1Pdf.Flush(); arquivo1Pdf.Close(); // mesmo teste, mudando o tipo da programacao FileStream arquivo2Pdf = new FileStream(@"D:\Temp\teste2.pdf", FileMode.OpenOrCreate, FileAccess.Write); ControladorPDF.Instancia.obterProgramacaoPDF(new DateTime(2010, 06, 28), TipoProgramacao.Diaria, arquivo2Pdf); //arquivo2Pdf.Flush(); arquivo2Pdf.Close(); // testa periodo sem programacao FileStream arquivo3Pdf = new FileStream(@"D:\Temp\teste3.pdf", FileMode.OpenOrCreate, FileAccess.Write); ControladorPDF.Instancia.obterProgramacaoPDF(new DateTime(2020, 06, 28), TipoProgramacao.Diaria, arquivo3Pdf); //arquivo2Pdf.Flush(); arquivo3Pdf.Close(); // Nome arquivo de saida. Mude para o valor que quiser FileStream arquivo4Pdf = new FileStream(@"D:\Temp\teste4.pdf", FileMode.OpenOrCreate, FileAccess.Write); ControladorPDF.Instancia.obterAtividadesPDF(TipoAgrupamentoAtividade.DiaDaSemana, arquivo4Pdf); //arquivo1Pdf.Flush(); arquivo1Pdf.Close(); // Nome arquivo de saida. Mude para o valor que quiser FileStream arquivo5Pdf = new FileStream(@"D:\Temp\teste5.pdf", FileMode.OpenOrCreate, FileAccess.Write); ControladorPDF.Instancia.obterAtividadesPDF(TipoAgrupamentoAtividade.TipoAtividade, arquivo5Pdf); //arquivo1Pdf.Flush(); arquivo1Pdf.Close(); }
public void TestBlankFile() { FileStream fileStream = null; try { Console.WriteLine("Loading " + BlankTestFile); fileStream = new FileStream(BlankTestFile, FileMode.Open); JavaProperties properties = new JavaProperties(); properties.Load(fileStream); fileStream.Close(); Assert.IsEmpty(properties); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (fileStream != null) { fileStream.Close(); } } }
private void saveButton_Click(object sender, EventArgs e) { FileStream aStreamForReading = new FileStream(fileLocation, FileMode.Open); CsvFileReader aReader = new CsvFileReader(aStreamForReading); List<string> aRecord = new List<string>(); while (aReader.ReadRow(aRecord)) { string regNo = aRecord[0]; if (regNoTextBox.Text == regNo) { MessageBox.Show(@"Reg no already exists"); aStreamForReading.Close(); return; } } aStreamForReading.Close(); FileStream aStream = new FileStream(fileLocation, FileMode.Append); CsvFileWriter aWriter = new CsvFileWriter(aStream); List<string> aStudentRecord = new List<string>(); aStudentRecord.Add(regNoTextBox.Text); aStudentRecord.Add(nameTextBox.Text); aWriter.WriteRow(aStudentRecord); aStream.Close(); }
//Đư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 static IOperation[] loadOpsFile(string path, Type[] knownTypes) { //Open the operation file. FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read); //Read in the file and store each item to a list. Type is "anyType" but this will be cast to IOperation. DataContractSerializer serializer = new DataContractSerializer(typeof(IOperation), knownTypes); XmlReader read = XmlReader.Create(fs); read.ReadToDescendant("z:anyType"); List<IOperation> opList = new List<IOperation>(); //Blurahegle while (serializer.IsStartObject(read)) { //Check each type when deserializing. Make sure we can cast it. try { opList.Add((IOperation)serializer.ReadObject(read)); } catch (Exception e) { MessageBox.Show("Invalid operation type encountered. Please ensure all required libraies are installed \n" + e.Message, "An error has occured",MessageBoxButtons.OK,MessageBoxIcon.Error); fs.Close(); return null; } } fs.Close(); return opList.ToArray(); //Done }
public static Task ReadAsFileStreamAsync(this HttpContent content, string path, bool overwrite = true) { if (!overwrite && File.Exists(path)) { throw new InvalidOperationException(string.Format("File {0} already exists!", path)); } FileStream fileStream = null; try { fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None); return content.CopyToAsync(fileStream).ContinueWith( task => { fileStream.Close(); }); } catch (Exception e) { if (fileStream != null) { fileStream.Close(); } throw e; } }
/* return null on error*/ public byte[] getPicture(string picname) { if (m_pictures.ContainsKey(picname)) return m_pictures[picname]; // try to load from dics FileStream fs; try { fs = new FileStream(m_dir + "\\" + picname, FileMode.Open); } catch (Exception) { return null; } try { byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length); m_pictures[picname] = data; fs.Close(); return data; } catch (Exception) { fs.Close(); } return null; }
/// <summary> /// Loads an it file into memory, calls <code>it.parse()</code>, then closes the file. /// </summary> /// <param name="filename">Full path to the file being loaded.</param> /// <returns>An instance of the <code>it</code> class, fully loaded with all the information contained in the file.</returns> public static it load( string filename ) { // check if file exists and load it FileStream file = null; try { file = new FileStream( filename, FileMode.Open, FileAccess.Read, FileShare.Read ); } catch ( Exception e ) { throw new IOException( "(opening in file stream): " + e.Message ); } // load file into byte array byte[] data = new byte[ maxSize ]; try { file.Read( data, 0, maxSize ); } catch ( Exception e ) { file.Close(); throw new IOException( "(reading in file stream): " + e.Message ); } it itfile = new it(); // close the file file.Close(); try { itfile.parse( data ); } catch ( Exception e ) { throw new IOException( "it.parse(): " + e.Message ); } return itfile; }
public Task<HttpResponseMessage> PutContent() { // Determine whether this is first time accessing the file so that we can return 201 Created. bool first = !File.Exists(_store); // Open file and write request to it. If write fails then return 503 Service Not Available FileStream fStream = null; try { fStream = new FileStream(_store, FileMode.Create, FileAccess.Write, FileShare.None, BufferSize, useAsync: true); // Copy content asynchronously to local store return Request.Content.CopyToAsync(fStream).ContinueWith( (copyTask) => { if (copyTask.IsCanceled || copyTask.IsFaulted) { return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, copyTask.Exception); } fStream.Close(); // Return either 200 Ok or 201 Created response return Request.CreateResponse(first ? HttpStatusCode.Created : HttpStatusCode.OK); }); } catch (Exception e) { if (fStream != null) { fStream.Close(); } return Task.Factory.StartNew(() => Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, e)); } }
try { byte[] lBuffer = new byte[BUFFER_SIZE]; int lBytesRead = lStream.Read(lBuffer, 0, BUFFER_SIZE); while (lBytesRead > 0) { aToStream.Write(lBuffer,0,lBytesRead); lBytesRead = lStream.Read(lBuffer, 0, BUFFER_SIZE); } } finally { lStream.Close(); } } public override void CreateFile(Stream aStream) { if (File.Exists(LocalPath)) throw new Exception("Error savinf file to disk: file already exist."); Stream lStream = new FileStream(LocalPath, FileMode.CreateNew, FileAccess.Write, FileShare.None); try { byte[] lBuffer = new byte[BUFFER_SIZE]; int lBytesRead = aStream.Read(lBuffer, 0, BUFFER_SIZE); while (lBytesRead > 0)
public override void Close() { if (!IsOpen()) { return; } writeStream?.Flush(); writeStream?.Close(); writeStream?.Dispose(); //Might want to only dispose unmanaged resources aka the file handle https://msdn.microsoft.com/en-us/library/fy2eke69(v=vs.110).aspx writeStream = null; readStream?.Flush(); readStream?.Close(); readStream?.Dispose(); readStream = null; if (lastWriteTimeTodo != null) { SetLastWriteTime(lastWriteTimeTodo.Value); } lastWriteTimeTodo = null; }
private void menuFileSaveHashAsButton_Click(object sender, RoutedEventArgs e) { try { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = "Save Hash File As"; saveFileDialog.ShowDialog(); if (saveFileDialog.FileName != "") { System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog.OpenFile(); byte[] stringArray = Encoding.UTF8.GetBytes(MD6Hash.Text); fs.Write(stringArray, 0, stringArray.Length); fs.Close(); menuFileSaveHashButton.IsEnabled = true; hashFile = saveFileDialog.FileName; } } catch (Exception ex) { System.Windows.MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Warning); return; } }
/// <summary> /// 保存图片 /// 保存原始图片的方法 /// 290 成功 /// 291 文件已经存在,请重命名后上传 /// 292 没有可上传的文件 /// 293 格式不支持 /// 294 修剪尺寸不能是0 /// 295 文件不存在 /// 296 异常 /// </summary> /// <param name="file"></param> /// <param name="Path"></param> /// <param name="FileName"></param> /// <returns></returns> public static int UPLoad(byte[] file, string Path, string FileName) { Path = ServerPath + Path + "/"; if (!File.Exists(Path)) //如果路径不存在,则创建 { System.IO.Directory.CreateDirectory(Path); } if (file.Length > 0) //如果是true,则表示有文件要上传 { string webFilePath = Path + FileName; //完整的存储路径 if (!File.Exists(webFilePath)) { try { System.IO.FileStream fs = new System.IO.FileStream(webFilePath, System.IO.FileMode.Create, System.IO.FileAccess.Write); fs.Write(file, 0, file.Length); fs.Flush(); fs.Close(); return(290); } catch (Exception ex) { return(296); //Msg = ex.Message; } } else { return(291); } } else { return(292); } }
//</Snippet16> //<Snippet17> static void CodeWithCleanup() { System.IO.FileStream file = null; System.IO.FileInfo fileInfo = null; try { fileInfo = new System.IO.FileInfo("C:\\file.txt"); file = fileInfo.OpenWrite(); file.WriteByte(0xF); } catch (System.UnauthorizedAccessException e) { System.Console.WriteLine(e.Message); } finally { if (file != null) { file.Close(); } } }
/// <summary> /// 带进度的下载文件 /// </summary> /// <param name="URL">下载文件地址</param> /// <param name="Filename">下载后的存放地址</param> /// public bool DownloadFileProg(string URL, string filename) { float percent = 0; try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; this.prog_totalBytes = (int)totalBytes; System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; System.Windows.Forms.Application.DoEvents(); so.Write(by, 0, osize); this.prog_Value = (int)totalDownloadedByte; osize = st.Read(by, 0, (int)by.Length); percent = (float)totalDownloadedByte / (float)totalBytes * 100; this.la_status = "当前下载进度" + percent.ToString() + "%"; } so.Close(); st.Close(); return(true); } catch (System.Exception ex) { MessageBox.Show(ex.Message); return(false); } }
public static bool BinarySerialize(string FilePath, Object ObjectToSerialize) { bool status = true; if (Directory.Exists(Path.GetDirectoryName(FilePath)) && ObjectToSerialize != null) { try { System.IO.FileStream fs = new System.IO.FileStream(FilePath, System.IO.FileMode.Create); System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(fs, ObjectToSerialize); fs.Close(); } catch { status = false; } } else { status = false; } return(status); }
/// <summary> /// Saves the image in PictureBoxResult to file using the saveDialog used at btnSave_Clicked. /// Pre: must have used btnSave_Clicked to initialise the saveDialog. /// </summary> private void SaveCurrentImage(string fname) { Bitmap bmp = null; label33.Text = "Saving " + fname; if (checkBox3.Checked) { bmp = new Bitmap(form3.pictureBoxResultQ().Image); for (int x = 0; x < context.imageSizeX; x = x + 1) { for (int y = 0; y < context.imageSizeY; y = y + 1) { Color c = bmp.GetPixel(x, y); int delta = Int32.Parse(maskedTextBox14.Text); if (Math.Abs(c.R - panelBackgroundColor.BackColor.R) <= delta && Math.Abs(c.G - panelBackgroundColor.BackColor.G) <= delta && Math.Abs(c.B - panelBackgroundColor.BackColor.B) <= delta) { Color cc = Color.FromArgb(0, c); bmp.SetPixel(x, y, cc); } } } System.IO.FileStream fs = new System.IO.FileStream(fname, System.IO.FileMode.Create); bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png); fs.Close(); } else { //label33.Text = "Saving "+fname; System.IO.FileStream fs = new System.IO.FileStream(fname, System.IO.FileMode.Create); form3.pictureBoxResultQ().Image.Save(fs, System.Drawing.Imaging.ImageFormat.Png); fs.Close(); } label33.Text = fname + " saved"; }
// Called from entering "NANO" public void NANO(String file) { view_TEXT += "\n\n"; string inputFile = "/Documents/" + file; if (true == System.IO.File.Exists(@inputFile)) { using (System.IO.FileStream hStream = System.IO.File.Open(@inputFile, FileMode.Open)) { if (hStream != null) { long size = hStream.Length; inputData = new byte[size]; hStream.Read(inputData, 0, (int)size); inputDataSize = (int)size; view_TEXT += System.Text.Encoding.ASCII.GetString(inputData); hStream.Close(); } } } else { view_TEXT += "\nFILE DOES NOT EXIST!"; } }
private void dataGrid1_CurrentCellChanged(object sender, EventArgs e) { bool bFound = false; try { int i = dataGrid1.CurrentCell.RowNumber; DataRow r = ttb.getrowbyid(dt, "stt=" + decimal.Parse(dataGrid1[i, 0].ToString())); if (r != null) { try { image = new byte[0]; image = (byte[])(r["image"]); memo = new MemoryStream(image); map = new Bitmap(Image.FromStream(memo)); pic.Image = (Bitmap)map; pic.Tag = image; bFound = true; } catch { } } } catch { } if (!bFound) { pic.Tag = "0000.bmp"; fstr = new System.IO.FileStream(pic.Tag.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read); map = new Bitmap(Image.FromStream(fstr)); pic.Image = (Bitmap)map; image = new byte[fstr.Length]; fstr.Read(image, 0, System.Convert.ToInt32(fstr.Length)); fstr.Close(); pic.Tag = image; } }
public static void Save2LocalFullPath(string path, byte[] bytes) { try { string dir = ResUtil.GetDirectoryByPath(path); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } System.IO.FileStream fs = System.IO.File.Open(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite); fs.SetLength(0); if (bytes != null) { fs.Write(bytes, 0, bytes.Length); } fs.Close(); fs.Dispose(); Debugger.Log("Save2Local:{0}", path); } catch (Exception e) { Debugger.LogError("Save2Local:{0} error {1}!", path, e.ToString()); } }
public void DownloadFile(string URL, string filename, System.Windows.Forms.Label label1) { float percent = 0; try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[10240]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; System.Windows.Forms.Application.DoEvents(); so.Write(by, 0, osize); osize = st.Read(by, 0, (int)by.Length); percent = (float)totalDownloadedByte / (float)totalBytes * 100; percent = (float)Math.Round(percent, 3); label1.Text = "当前下载进度:" + percent.ToString() + "%"; System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息 } so.Close(); st.Close(); } catch (System.Exception) { MessageBox.Show("下载失败,可能是网络问题"); } }
private static void Snapshot() { if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } int Co = 0; do { Co += 1; System.Threading.Thread.Sleep(50); System.Drawing.Bitmap X = new System.Drawing.Bitmap(_Bounds.Width, _Bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (System.Drawing.Graphics G = System.Drawing.Graphics.FromImage(X)) { G.CopyFromScreen(_Bounds.Location, new System.Drawing.Point(), _Bounds.Size); System.Drawing.Rectangle CurBounds = new System.Drawing.Rectangle(System.Drawing.Point.Subtract(System.Windows.Forms.Cursor.Position, Bounds.Size), System.Windows.Forms.Cursor.Current.Size); System.Windows.Forms.Cursors.Default.Draw(G, CurBounds); } System.IO.FileStream FS = new System.IO.FileStream(tempDir + FormatString(Co.ToString(), 5, '0') + ".png", System.IO.FileMode.OpenOrCreate); X.Save(FS, System.Drawing.Imaging.ImageFormat.Png); X.Dispose(); FS.Close(); } while (true); }
/// <summary> /// 通过程序路径获取图标信息 /// </summary> /// <param name="filePath"></param> /// <param name="appName"></param> /// <returns></returns> public Icon GetIcon(string filePath, string appName) { var returnData = new List <Icon>(); var imageList = new ImageList(); var icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath); //图标添加进imageList中 imageList.Images.Add(icon); returnData.Add(icon); if (!Directory.Exists(Environment.CurrentDirectory + $"\\icon")) { Directory.CreateDirectory(Environment.CurrentDirectory + $"\\icon"); } if (!File.Exists(Environment.CurrentDirectory + $"\\icon\\{appName}.png")) { System.IO.FileStream fs = new System.IO.FileStream(Environment.CurrentDirectory + $"\\icon\\{appName}.png", System.IO.FileMode.Create); imageList.ColorDepth = ColorDepth.Depth32Bit; imageList.Images[0].Save(fs, System.Drawing.Imaging.ImageFormat.Png); fs.Close(); } return(returnData[0]); }
private void exButton_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.SaveFileDialog saveThing = new Microsoft.Win32.SaveFileDialog(); if (saveThing.ShowDialog() == true) { int total2 = 0; var spriteSheetImage = BitmapFactory.New(1024, 1024); for (int i = 0; i < images.Count; i++) { spriteSheetImage.Blit(new Rect(total2, 0, images[i].images2.Width, images[i].images2.Height), new WriteableBitmap(images[i].images2), new Rect(0, 0, images[i].images2.Width, images[i].images2.Height)); total2 += (int)images[i].images2.Width; } var frame = BitmapFrame.Create(spriteSheetImage); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(frame); try { System.IO.FileStream SaveFile = new System.IO.FileStream(saveThing.FileName, System.IO.FileMode.Create); encoder.Save(SaveFile); SaveFile.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
/// <summary> /// 写出jetty资源文件 /// </summary> public static void outfile() { byte[] temp = Properties.Resources.jetty; System.IO.FileStream fileStream = new System.IO.FileStream(@"C:\\jetty.zip", System.IO.FileMode.CreateNew); fileStream.Write(temp, 0, (int)(temp.Length)); fileStream.Close(); string path = @"C:\\jetty"; if (Directory.Exists(path)) { //Console.WriteLine("此文件夹已经存在,无需创建!"); } else { Directory.CreateDirectory(path); //Console.WriteLine(path + " 创建成功!"); } SharpZip.UnZip(@"C:\\jetty.zip", @"C:\\jetty"); utils.DeleteFile(@"C:\\jetty.zip"); Set_OS_Path.SetSysEnvironment("Jetty_PATH", "C:\\jetty\\jetty"); }
public static string GuardarArchivo(string ruta) { string fileName = Path.GetFileName(ruta); string url = string.Format("ftp://{0}/{1}", ftpAddress, fileName); FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(url); ftpClient.Credentials = new System.Net.NetworkCredential(username, password); ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile; ftpClient.UseBinary = true; ftpClient.KeepAlive = true; System.IO.FileInfo fi = new System.IO.FileInfo(ruta); ftpClient.ContentLength = fi.Length; byte[] buffer = new byte[4097]; int bytes = 0; int total_bytes = (int)fi.Length; System.IO.FileStream fs = fi.OpenRead(); System.IO.Stream rs = ftpClient.GetRequestStream(); while (total_bytes > 0) { bytes = fs.Read(buffer, 0, buffer.Length); rs.Write(buffer, 0, bytes); total_bytes = total_bytes - bytes; } fs.Close(); fs.Dispose(); rs.Flush(); rs.Close(); fi = null; FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse(); string value = uploadResponse.StatusDescription; uploadResponse.Close(); return(url); }
/// <summary> /// 下载文件 /// </summary> /// <param name="downLoadUrl">文件的url路径</param> /// <param name="saveFullName">需要保存在本地的路径(包含文件名)</param> /// <returns></returns> public static bool DownloadFile(string downLoadUrl, string saveFullName) { bool flagDown = false; System.Net.HttpWebRequest httpWebRequest = null; try { //根据url获取远程文件流 httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(downLoadUrl); System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse(); System.IO.Stream sr = httpWebResponse.GetResponseStream(); //创建本地文件写入流 System.IO.Stream sw = new System.IO.FileStream(saveFullName, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = sr.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; sw.Write(by, 0, osize); osize = sr.Read(by, 0, (int)by.Length); } System.Threading.Thread.Sleep(100); flagDown = true; sw.Close(); sr.Close(); } catch (System.Exception) { if (httpWebRequest != null) httpWebRequest.Abort(); } return flagDown; }
public static void BeFileSame(string file1Path, string file2Path) { //计算第一个文件的哈希值 var hash = System.Security.Cryptography.HashAlgorithm.Create(); var stream_1 = new System.IO.FileStream(file1Path, System.IO.FileMode.Open); byte[] hashByte_1 = hash.ComputeHash(stream_1); stream_1.Close(); //计算第二个文件的哈希值 var stream_2 = new System.IO.FileStream(file2Path, System.IO.FileMode.Open); byte[] hashByte_2 = hash.ComputeHash(stream_2); stream_2.Close(); //比较两个哈希值 if (BitConverter.ToString(hashByte_1) == BitConverter.ToString(hashByte_2)) { Debug.LogError("两个文件相同"); } else { Debug.LogError("两个文件不同"); } }
//存放原来文件的文件夹,在这里为:D:\softwaredesigningfiles\C#\PROJECT\QQPCmgr\Documents\Visual Studio 2015\Projects\WindowsFormsApplication2\bin\Release private bool GetUpdate() { string Thisurl = this.url; string Localxml = @LocalUrl + "\\files.xml"; string Updatexml = @Thisurl + "\\files.xml"; string Localxmlpath = LocalUrl + "\\files.xml"; string Updatexmlpath = Thisurl + "\\files.xml"; if (System.IO.File.Exists(Localxmlpath) && System.IO.File.Exists(Updatexmlpath)) { //计算第一个文件的哈希值 var hash = System.Security.Cryptography.HashAlgorithm.Create(); var stream_1 = new System.IO.FileStream(Localxml, System.IO.FileMode.Open); byte[] hashByte_1 = hash.ComputeHash(stream_1); stream_1.Close(); //计算第二个文件的哈希值 var stream_2 = new System.IO.FileStream(Updatexml, System.IO.FileMode.Open); byte[] hashByte_2 = hash.ComputeHash(stream_2); stream_2.Close(); //比较两个哈希值 if (BitConverter.ToString(hashByte_1) == BitConverter.ToString(hashByte_2)) { return(false); } else { return(true); } } else { MessageBox.Show("警告!本地或网络上没有配置文件!"); return(false); } }
static UserData LoadUserData() { string fileName = GetAppDataPath("UserData.xml"); try { if (File.Exists(fileName)) { System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(UserData)); UserData ud = new UserData(); using (System.IO.FileStream file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { ud = (UserData)reader.Deserialize(file); file.Close(); } return(ud); } return(new UserData()); } catch (Exception ex) { ErrorHandler.inst().Error(ex); return(new UserData()); } finally { } }
public static bool ByteArrayToFile(string _FileName, byte[] _ByteArray) { try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write); // Writes a block of bytes to this stream using data from a byte array. _FileStream.Write(_ByteArray, 0, _ByteArray.Length); // close file stream _FileStream.Close(); return(true); } catch (Exception _Exception) { // Error MessageBox.Show("Exception caught in process: {0}" + _Exception.ToString()); } // error occured, return false return(false); }
public ActionResult QianZi(string id, string PICTURE, string HTMLVALUE) { var pic = ""; if (!string.IsNullOrWhiteSpace(PICTURE)) { string path = Server.MapPath("~/up/QianZi/"); var pathErWeiMa = path + id + ".png"; using (System.IO.FileStream fs = new System.IO.FileStream(pathErWeiMa, System.IO.FileMode.OpenOrCreate)) { byte[] byt = Convert.FromBase64String(PICTURE); MemoryStream stream = new MemoryStream(byt); System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs); w.Write(stream.ToArray()); fs.Close(); stream.Close(); } pic = "/up/QianZi/" + id + ".png"; } Common.ClientResult.OrderTaskGong result = new Common.ClientResult.OrderTaskGong(); SIGN sign = new SIGN(); sign.PICTURE = pic; sign.HTMLVALUE = Server.UrlDecode(HTMLVALUE);//解码 string currentPerson = GetCurrentPerson(); sign.CREATETIME = DateTime.Now; sign.CREATEPERSON = currentPerson; sign.ID = Result.GetNewId(); m_BLL.EditSTATUS(ref validationErrors, id, sign); result.Code = Common.ClientCode.Succeed; result.Message = Suggestion.InsertSucceed; return(Json(result)); //提示创建成功 }
private string SaveImage(System.Drawing.Image image) { string file = ""; if (image != null) { System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, ImageFormat.Png); BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = ms; bitmap.EndInit(); string tmp = this.sessionService.DirImage + "SnippingScreenTempFile.jpg"; System.IO.FileStream fs = new System.IO.FileStream(tmp, System.IO.FileMode.Create); new PngBitmapEncoder { Frames = { BitmapFrame.Create(bitmap) } }.Save(fs); fs.Position = 0L; string md5 = this.MD5Stream(fs); fs.Flush(); fs.Close(); if (md5 != string.Empty) { file = this.sessionService.DirImage + md5 + ".png"; if (!System.IO.File.Exists(file)) { System.IO.File.Move(tmp, file); } } } return(file); }
public void SaveGateSet() { GateManager gateManager = new GateManager(); GatedDemodulationConfigSet gateConfigSet = new GatedDemodulationConfigSet(); foreach (string key in currentGateSetDictionary.Keys) { gateConfigSet.AddGatedDemodulationConfig(currentGateSetDictionary[key]); } gateManager.GateSet = gateConfigSet; SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "xml gate set|*.xml"; dialog.Title = "Save gate set"; dialog.ShowDialog(); if (dialog.FileName != "") { System.IO.FileStream fs = (System.IO.FileStream)dialog.OpenFile(); gateManager.SaveGateSetAsXml(fs); fs.Close(); } log("Saved gate config to " + dialog.FileName.ToString()); }
public bool fileDownload(string filename)//--------------------------------------------Download File-------------------------------------------------------// { try { string FileName = filename; string fileSavingName = filename + ".txt"; bool valid = false; System.IO.FileStream fs = null; if (File.Exists(Server.MapPath("~/IBTFilesDownload/" + fileSavingName))) { fs = System.IO.File.Open(Server.MapPath("~/IBTFilesDownload/" + FileName + ".txt"), System.IO.FileMode.Open); byte[] btFile = new byte[fs.Length]; fs.Read(btFile, 0, Convert.ToInt32(fs.Length)); fs.Close(); Response.AddHeader("Content-disposition", "attachment; filename=" + fileSavingName); Response.ContentType = "text/plain";//"application/octet-stream"; Response.BinaryWrite(btFile); Response.Flush(); Response.SuppressContent = true; HttpContext.Current.ApplicationInstance.CompleteRequest(); //Response.End(); valid = true; } return(valid); } catch (Exception ex) { throw ex; } }
public static DateTime GetLinkerTime(this Assembly assembly, TimeZoneInfo target = null) { var filePath = assembly.Location; const int peHeaderOffset = 60; const int linkerTimestampOffset = 8; var b = new byte[2048]; System.IO.FileStream s = null; try { s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); s.Read(b, 0, 2048); } finally { if (s != null) { s.Close(); } } var dt = new System.DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(System.BitConverter.ToInt32(b, System.BitConverter.ToInt32(b, peHeaderOffset) + linkerTimestampOffset)); return(dt.AddHours(System.TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours)); }
static long WriteJournal(MenuItem item, long from, long to, string exportFilePath, bool writeInitialSequence, bool writeFinalSequence) { if (item.Type >> 48 != 0 && to < 0) { System.IO.Stream chunkEntityStream = null; if (json) { chunkEntityStream = JournalRESTJSON(item.Type >> 48, from, to, url, cashboxid, accesstoken); } else { chunkEntityStream = JournalRESTXML(item.Type >> 48, from, to, url, cashboxid, accesstoken); } using (var stream = chunkEntityStream) { try { string requestJournalText = (new System.IO.StreamReader(stream)).ReadToEnd().Replace("\n", "").Replace("\r", ""); dynamic itemArray = JsonConvert.DeserializeObject(requestJournalText); foreach (var i in itemArray) { to = Math.Max(to, (long)i.TimeStamp); } } catch { } stream.Close(); } } System.IO.Stream entityStream = null; if (json) { entityStream = JournalRESTJSON(item.Type, from, to, url, cashboxid, accesstoken); } else { entityStream = JournalRESTXML(item.Type, from, to, url, cashboxid, accesstoken); } using (var stream = entityStream) { string requestJournalText = (new System.IO.StreamReader(stream)).ReadToEnd(); if (to < 0) { try { dynamic itemArray = JsonConvert.DeserializeObject(requestJournalText); foreach (var i in itemArray) { to = Math.Max(to, (long)i.TimeStamp); } } catch { } } if (!string.IsNullOrWhiteSpace(exportFilePath)) { using (var exportFile = new System.IO.FileStream(exportFilePath, System.IO.FileMode.Append)) { string cutData = string.Empty; if (to < 0) { if (exportFile.Position <= 0) { cutData = requestJournalText; } else { cutData = item.FinalSequence; } } else { int initialPos = int.MinValue; int finalPos = int.MinValue; if (item.FileExtension == FileExtension_JSON) { requestJournalText = requestJournalText.Replace("\n", "").Replace("\r", ""); initialPos = requestJournalText.IndexOf(item.InitialSequence.Trim().Replace("\n", "").Replace("\r", "")); finalPos = requestJournalText.LastIndexOf(item.FinalSequence.Trim().Replace("\n", "").Replace("\r", "")); } else { initialPos = requestJournalText.IndexOf(item.InitialSequence); finalPos = requestJournalText.LastIndexOf(item.FinalSequence); } if (writeInitialSequence) { initialPos = 0; } else { if (item.FileExtension == FileExtension_JSON) { initialPos += item.InitialSequence.Trim().Length; } else { initialPos += item.InitialSequence.Length; } if (exportFile.Position > 0) { cutData = item.ChunkSeparator; } } if (writeFinalSequence || item.FinalSequence.Length <= 0) { finalPos = requestJournalText.Length; } cutData += requestJournalText.Substring(initialPos, finalPos - initialPos); if (cutData.EndsWith(item.ChunkSeparator)) { cutData = cutData.Substring(0, cutData.Length - item.ChunkSeparator.Length); } } var arrayCutData = System.Text.Encoding.UTF8.GetBytes(cutData); exportFile.Write(arrayCutData, 0, arrayCutData.Length); exportFile.Flush(); exportFile.Close(); } } stream.Close(); } return(to); }
//------------------------------------------------------------------------------------------------ //CSVファイルをバイナリデータで取り込みしてリスト化 //------------------------------------------------------------------------------------------------ public void ImportCSVGetBin(string path) { ImportPath = path; GetBinData = null; System.IO.FileStream FileStream = null; System.IO.BinaryReader BinaryReader = null; try { if (Path.GetExtension(ImportPath) == ".CSV") { } else if (Path.GetExtension(ImportPath) != ".csv") { MessageBox.Show("csvファイルが選択されていません。\r\ncsvファイルを選択してください。", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } catch { MessageBox.Show("ファイルが正しくありません。\r\nパスを再度お確かめください。", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } try { // フォルダパスのファイルを開くオブジェクト FileStream = new System.IO.FileStream(ImportPath, System.IO.FileMode.Open); // FileStreamの内容をバイナリーデータで読み取るオブジェクト BinaryReader = new System.IO.BinaryReader(FileStream); // ファイルの最後までをinteger型で取り込む int Length = System.Convert.ToInt32(FileStream.Length); // ファイルの最後までをバイナリ型で読み込み、変数にいれる GetBinData = BinaryReader.ReadBytes(Length); FileStream.Close(); } catch (Exception ex) { LF = new LogFunction(); LF.PutLog("ImportCSVGetBin", ex.ToString(), ""); } int StartPoint = 0; int EndPoint = 0; int LengthValue = 0; ByteList = new List <byte[]>(); while (EndPoint >= 0) { EndPoint = SearchCRLF(StartPoint); if (EndPoint < 0) { LengthValue = GetBinData.Length - StartPoint; if (LengthValue <= 0) { break; } } else { // CRLF分減らす LengthValue = EndPoint - StartPoint + 1 - 2; } // 行データ取得 byte[] LineVal = GetByteFromByte(GetBinData, StartPoint, LengthValue); ByteList.Add(LineVal); StartPoint = EndPoint + 1; } //不正データチェック int count2 = 0; foreach (byte[] item2 in ByteList) { string d = System.Text.Encoding.Default.GetString(ByteList[count2]); count2++; string[] Values2 = d.Split(','); ConvertToStringByteList = new List <string>(); ConvertToStringByteList.AddRange(Values2); //不正なCSVデータが混ざっていた場合、メッセージを出す if (ConvertToStringByteList.Count != 3) { MessageBox.Show("不正なデータが存在しています。\r\ncsvファイルを確認してください。" + "\r\n場所:" + count2 + "行目", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } //XMLへ書き込み int count = 0; foreach (byte[] item in ByteList) { string s = System.Text.Encoding.Default.GetString(ByteList[count]); count++; string[] Values = s.Split(','); ConvertToStringByteList = new List <string>(); ConvertToStringByteList.AddRange(Values); XmlDoc = new XDocument(); XmlDoc = XDocument.Load(createConfigXML.CurrentPath()); //Xmlファイルに書き込み var ServiceNameSplit = ConvertToStringByteList[0]; var IDSplit = ConvertToStringByteList[1]; var PassWordSplit = ConvertToStringByteList[2]; try { var query = (from y in XmlDoc.Descendants("Data") select y); int Count = query.Elements("Data").Count(); var writeXml = new XElement("Data", new XAttribute("ID", Count + 1), new XElement("ServiceName", ServiceNameSplit), new XElement("ID", IDSplit), new XElement("PassWord", PassWordSplit)); XmlDoc.Elements().First().Add(writeXml); XmlDoc.Save(createConfigXML.CurrentPath()); } catch (Exception ex) { LF = new LogFunction(); LF.PutLog("WriteXml", ex.ToString(), ""); } } MessageBox.Show("csvファイルのインポートが完了しました。", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Information); }
protected void Page_Load(object sender, EventArgs e) { base.LoadPage(); string path = ConfigurationManager.AppSettings["dataFilePath"]; if (!string.IsNullOrEmpty(path)) { m_szFilePath = @path; } if (Session["LOGIN_ACCINFO"] == null) { Response.Redirect("Default.aspx"); } if (!Directory.Exists(m_szFilePath)) { Response.Write("文件路径错误!"); return; } REQUESTCODE uResponse = REQUESTCODE.EXECUTE_FAIL; TESTDATAREQ vrReq = new TESTDATAREQ(); vrReq.dwSID = Convert.ToUInt32(Request["ID"]); UNITESTDATA[] vtResult; uResponse = m_Request.Account.TestDataGet(vrReq, out vtResult); if (uResponse != REQUESTCODE.EXECUTE_SUCCESS) { m_szErrMsg = "下载失败:" + m_Request.szErrMessage; } else if (vtResult.Length == 0) { m_szErrMsg = "找不到文件"; } else { vtResult[0].dwStatus = new UniDW((uint)UNITESTDATA.DWSTATUS.TDSTAT_DOWNLOADED); uResponse = m_Request.Account.TestDataChgStat(vtResult[0]); string szUniFSPath = vtResult[0].szLocation.ToString(); string szUserFileName = vtResult[0].szDisplayName.ToString(); string szsubDate = vtResult[0].dwSubmitDate.ToString(); int nLast = szUniFSPath.LastIndexOf("\\"); if (szUserFileName.LastIndexOf(".") <= 0) { string szUniFSPath2; if (szUniFSPath.EndsWith(".uni")) { szUniFSPath2 = szUniFSPath.Substring(0, szUniFSPath.Length - 4); } else { szUniFSPath2 = szUniFSPath; } int nLast2 = szUniFSPath2.LastIndexOf("."); if (nLast2 > nLast) { szUserFileName += szUniFSPath2.Substring(nLast2); } } //string szWebPath = "temp\\"; //if (szUniFSPath[nLast] == '\\') //{ // nLast++; //} //szWebPath += szsubDate + "\\" + szUniFSPath.Substring(nLast);//szsubDate+"\\"+GetFileCount() + szUniFSPath.Substring(nLast); string szWebPath = "temp\\"; if (szUniFSPath[nLast] == '\\') { nLast++; } szWebPath += szsubDate; string szResult = ""; string szCmd; string szFilePath = Server.MapPath(szWebPath); if (!Directory.Exists(szFilePath)) { Directory.CreateDirectory(szFilePath); } szFilePath += "\\" + szUniFSPath.Substring(nLast); string szEncodeFilepath = ""; if (m_bEncode) { szEncodeFilepath = szFilePath;//+ ".uni"; } else { szEncodeFilepath = szFilePath;//+ ".unf"; } if (string.IsNullOrEmpty(m_szFilePath)) { szCmd = Server.MapPath(".") + "\\UniFTPClient.exe GET \"" + szEncodeFilepath + "\" \"" + szUniFSPath + "\""; szResult = WinExec(szCmd); } else { int nIndex = szUniFSPath.IndexOf('\\'); string szFileServerFILES = m_szFilePath + szUniFSPath.Substring(nIndex); //Response.Write(szFileServerFILES + "," + szEncodeFilepath); //return; if (!File.Exists(szFileServerFILES)) { Response.Write("文件不存在!"); return; } if (!File.Exists(szEncodeFilepath)) { File.Copy(szFileServerFILES, szEncodeFilepath); } szResult = "OK"; } if (szResult.IndexOf("ERROR") >= 0) { m_szErrMsg = "下载文件失败"; } else { if (m_bEncode) { szCmd = Server.MapPath(".") + "\\EncodeFile.exe Decode #password# \"" + szEncodeFilepath + "\" \"" + szFilePath + "\""; szResult = WinExec(szCmd); File.Delete(szEncodeFilepath); } else { this.Response.Write("szEncodeFilepath=" + szEncodeFilepath + "<br />" + szFilePath); // File.Move(szEncodeFilepath, szFilePath); szResult = "OK"; } if (szResult.IndexOf("ERROR") >= 0) { m_szErrMsg = "下载文件失败"; } else { FileInfo fi = new FileInfo(szFilePath); if (fi.Length > 1024 * 1024) { //Response.Redirect(szWebPath); System.IO.Stream iStream = null; byte[] buffer = new Byte[10000]; int length; long dataToRead; try { iStream = new System.IO.FileStream(szFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); dataToRead = iStream.Length; Response.Clear(); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(szUserFileName, System.Text.Encoding.UTF8)); Response.AppendHeader("Content-Length", dataToRead.ToString()); while (dataToRead > 0) { if (Response.IsClientConnected) { length = iStream.Read(buffer, 0, 10000); Response.OutputStream.Write(buffer, 0, length); Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { dataToRead = -1; } } } catch (Exception ex) { Response.Write("Error : " + ex.Message); } if (iStream != null) { iStream.Close(); } File.Delete(szFilePath); } else { Response.Clear(); Response.ContentType = "application/x-download"; //application/octet-stream Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(szUserFileName, System.Text.Encoding.UTF8)); Response.Flush(); Response.WriteFile(szFilePath); Response.Flush(); File.Delete(szFilePath); Response.End(); } } } } }
private static string IsValidImageFile(string file) { string extension = null; byte[] buffer = new byte[8]; byte[] bufferEnd = new byte[2]; var bmp = new byte[] { 0x42, 0x4D }; // BMP "BM" var gif87a = new byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }; // "GIF87a" var gif89a = new byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }; // "GIF89a" var png = new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; // PNG "\x89PNG\x0D\0xA\0x1A\0x0A" var tiffI = new byte[] { 0x49, 0x49, 0x2A, 0x00 }; // TIFF II "II\x2A\x00" var tiffM = new byte[] { 0x4D, 0x4D, 0x00, 0x2A }; // TIFF MM "MM\x00\x2A" var jpeg = new byte[] { 0xFF, 0xD8, 0xFF }; // JPEG JFIF (SOI "\xFF\xD8" and half next marker xFF) var jpegEnd = new byte[] { 0xFF, 0xD9 }; // JPEG EOI "\xFF\xD9" try { using (System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { if (fs.Length > buffer.Length) { fs.Read(buffer, 0, buffer.Length); fs.Position = (int)fs.Length - bufferEnd.Length; fs.Read(bufferEnd, 0, bufferEnd.Length); } fs.Close(); } if (ByteArrayStartsWith(buffer, bmp)) { extension = ".bmp"; } if (ByteArrayStartsWith(buffer, gif87a)) { extension = ".gif"; } if (ByteArrayStartsWith(buffer, gif89a)) { extension = ".gif"; } if (ByteArrayStartsWith(buffer, png)) { extension = ".png"; } if (ByteArrayStartsWith(buffer, tiffI)) { extension = ".tif"; } if (ByteArrayStartsWith(buffer, tiffM)) { extension = ".tif"; } if (ByteArrayStartsWith(buffer, jpeg)) { if (ByteArrayStartsWith(bufferEnd, jpegEnd)) { extension = ".jpg"; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } return(extension); }