public Read ( byte array, int offset, int count ) : int | ||
array | byte | |
offset | int | |
count | int | |
Résultat | int |
public static DateTime GetBuildDateTime() { var assembly = Assembly.GetCallingAssembly(); if (File.Exists(assembly.Location)) { var buffer = new byte[Math.Max(Marshal.SizeOf(typeof (_IMAGE_FILE_HEADER)), 4)]; using (var fileStream = new FileStream(assembly.Location, FileMode.Open, FileAccess.Read)) { fileStream.Position = 0x3C; fileStream.Read(buffer, 0, 4); fileStream.Position = BitConverter.ToUInt32(buffer, 0); // COFF header offset fileStream.Read(buffer, 0, 4); // "PE\0\0" fileStream.Read(buffer, 0, buffer.Length); } var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { var coffHeader = (_IMAGE_FILE_HEADER) Marshal.PtrToStructure(pinnedBuffer.AddrOfPinnedObject(), typeof (_IMAGE_FILE_HEADER)); return TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1) + new TimeSpan(coffHeader.TimeDateStamp*TimeSpan.TicksPerSecond)); } finally { pinnedBuffer.Free(); } } return new DateTime(); }
/** * Constructor * * @param file the file * @param propertySet the property set to read * @param os the output stream * @exception IOException * @exception BiffException */ public PropertySetsReader(FileInfo file, string propertySet, TextWriter os) { //writer = new BufferedWriter(new OutputStreamWriter(os)); Stream fis = new FileStream(file.Name,FileMode.Open,FileAccess.Read); int initialFileSize = 1024 * 1024; // 1mb int arrayGrowSize = 1024 * 1024;// 1mb byte[] d = new byte[initialFileSize]; int bytesRead = fis.Read(d,0,d.Length); int pos = bytesRead; while (bytesRead != -1) { if (pos >= d.Length) { // Grow the array byte[] newArray = new byte[d.Length + arrayGrowSize]; Array.Copy(d, 0, newArray, 0, d.Length); d = newArray; } bytesRead = fis.Read(d, pos, d.Length - pos); pos += bytesRead; } bytesRead = pos + 1; compoundFile = new CompoundFile(d, new WorkbookSettings()); fis.Close(); if (propertySet == null) displaySets(os); else displayPropertySet(propertySet, os); }
public bool TryReadRom(FileStream rom, out string RomId, out string RomType) { // .N64 file header // 0x20-0x33 - Game Name // 0x34-0x38 - Null RomId = null; RomType = null; byte[] magicNumberArry = new byte[8]; rom.Position = 0x34; rom.Read(magicNumberArry, 0, 5); long magicNumber = BitConverter.ToInt64(magicNumberArry, 0); if(magicNumber != 0) { return false; } RomType = "Nintendo 64"; byte[] romIdArray = new byte[20]; rom.Position = 0x20; rom.Read(romIdArray, 0, 20); RomId = Encoding.ASCII.GetString(romIdArray).TrimEnd('\0'); return true; }
public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize) { //如果文件没有找到,则报错 if (!System.IO.File.Exists(FileToZip)) { throw new System.IO.FileNotFoundException("The specified file " + FileToZip + " could not be found. Zipping aborderd"); } System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile); ZipOutputStream ZipStream = new ZipOutputStream(ZipFile); ZipEntry ZipEntry = new ZipEntry("ZippedFile"); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(CompressionLevel); byte[] buffer = new byte[BlockSize]; System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length); ZipStream.Write(buffer, 0, size); try { while (size < StreamToZip.Length) { int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length); ZipStream.Write(buffer, 0, sizeRead); size += sizeRead; } } catch (System.Exception ex) { throw ex; } ZipStream.Finish(); ZipStream.Close(); StreamToZip.Close(); }
private Stream LocateCode() { var fileName = System.Reflection.Assembly.GetExecutingAssembly().Location; using(var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { const int SIGN_SIZE = 8; fs.Position = fs.Length - SIGN_SIZE; byte[] signature = new byte[SIGN_SIZE]; fs.Read(signature, 0, SIGN_SIZE); if (signature[0] == 0x4f && signature[1] == 0x53 && signature[2] == 0x4d && signature[3] == 0x44) { int codeOffset = BitConverter.ToInt32(signature, 4); long codeLen = fs.Length - codeOffset - SIGN_SIZE; fs.Seek(codeOffset, SeekOrigin.Begin); byte[] code = new byte[codeLen]; fs.Read(code, 0, (int)codeLen); var ms = new MemoryStream(code); return ms; } else { throw new InvalidOperationException("No module found"); } } }
/* * ushort MachoNetVersion = 320; double EVEVersionNumber = 7.31; int EVEBuildVersion = 360229; string EVEProjectCodename = "EVE-EVE-TRANQUILITY"; string EVEProjectRegion = "ccp"; string EVEProjectVersion = "EVE-EVE-TRANQUILITY@ccp"; */ static void Main() { byte GzipMarker = 126; // 0x7E // Has 60 bytes worth of raw packet data FileStream stream = new FileStream("ExportedStamp", FileMode.Open); int PacketLengthMarker = 0; ushort Machonet = 0; // Resize for Int32 Buffer byte[] buffer = new byte[4]; stream.Read(buffer, 0, 4); // It's a packet length in worth of data (Purpose of GZip, // otherwise it'd be retarded since TCP protocol already covered that.) PacketLengthMarker = BitConverter.ToInt32(buffer, 0); // Gzip Stream isn't necessary, because it already extracted via 7E marker. //var fixStream = new DeflateStream(stream, CompressionMode.Decompress); stream.Read(buffer, 0, 1); // This is 7E marker stream.Read(buffer, 0, 4); // This is the unknown marker that occupy 4 bytes of the marshal stream buffer = new byte[2]; stream.Read(buffer, 0, 2); Machonet = BitConverter.ToUInt16(buffer, 0); //Machonet = BitConverter.ToUInt16(buffer, 0); Console.WriteLine("Packet Size: " + PacketLengthMarker); Console.WriteLine("Machonet: " + Machonet); Console.ReadLine (); }
public int UploadWebDavFile(string _WebFileUrl, string _LocalFile, string _UserName, string _Password) { try { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)WebRequest.Create(_WebFileUrl); //Http和服务器交互 req.Credentials = new NetworkCredential(_UserName, _Password); //验证密码 req.PreAuthenticate = true; req.Method = "PUT";//采用PUT方式 req.AllowWriteStreamBuffering = true; Stream reqStream = req.GetRequestStream(); FileStream rdm = new FileStream(_LocalFile, FileMode.Open); //打开本地文件流 byte[] inData = new byte[4096]; int byteRead = rdm.Read(inData, 0, inData.Length); //二进制读文件 while (byteRead > 0) { reqStream.Write(inData, 0, byteRead); //响应流写入 byteRead = rdm.Read(inData, 0, inData.Length); } rdm.Close(); reqStream.Close(); req.GetResponse(); //提交 } catch { return 0; } return 1; //正确返回 }
public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize) { if (!File.Exists(FileToZip)) { throw new FileNotFoundException("The specified file " + FileToZip + " could not be found. Zipping aborderd"); } FileStream fileStream = new FileStream(FileToZip, FileMode.Open, FileAccess.Read); FileStream baseOutputStream = File.Create(ZipedFile); ZipOutputStream zipOutputStream = new ZipOutputStream(baseOutputStream); ZipEntry entry = new ZipEntry("ZippedFile"); zipOutputStream.PutNextEntry(entry); zipOutputStream.SetLevel(CompressionLevel); byte[] array = new byte[BlockSize]; int num = fileStream.Read(array, 0, array.Length); zipOutputStream.Write(array, 0, num); try { while ((long)num < fileStream.Length) { int num2 = fileStream.Read(array, 0, array.Length); zipOutputStream.Write(array, 0, num2); num += num2; } } catch (Exception ex) { throw ex; } zipOutputStream.Finish(); zipOutputStream.Close(); fileStream.Close(); }
// ----- ----- ----- PRIVATE ----- ----- ----- private void LoadUnits(string dir, List<UnitData> list, bool createMaster, bool createCommon, bool createUnique) { string filePath = Path.Combine(dir, "CharacterData"); using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read)) using (var reader = new BinaryReader(file)){ reader.ReadInt32(); // 0x8C == 140固定? int charaEndNum = reader.ReadInt32(); int masterEndNum = reader.ReadInt32(); int commonEndNum = reader.ReadInt32(); int uniqueEndNum = reader.ReadInt32(); if (createMaster) { int count = masterEndNum - 1; var buff = new byte[count * UNIT_SIZE]; file.Read(buff, OFFSET, buff.Length); var m = new MemoryStream(buff); } if (createMaster) { int count = commonEndNum - masterEndNum; var buff = new byte[count * UNIT_SIZE]; file.Read(buff, OFFSET + masterEndNum * UNIT_SIZE, buff.Length); var m = new MemoryStream(buff); } if (createMaster) { int count = uniqueEndNum - commonEndNum; var buff = new byte[count * UNIT_SIZE]; file.Read(buff, OFFSET + commonEndNum * UNIT_SIZE, buff.Length); var m = new MemoryStream(buff); } } }
//WriteRIFFStream // Function to read a 16 bit/sample mono wave file and return intSampleRate and the sampled data in bytWaveData() public bool ReadRIFF(string strFilename, ref int intSampleRate, ref byte[] bytWaveData) { // returns true if successful, false if not. intSampleRate and bytWaveData updated by reference if (!System.IO.File.Exists(strFilename)) return false; try { FileStream fs = new FileStream(strFilename, FileMode.Open); byte[] bytHeader = new byte[46]; fs.Read(bytHeader, 0, 46); int intFmtChunkLength = System.BitConverter.ToInt32(bytHeader, 16); intSampleRate = System.BitConverter.ToInt32(bytHeader, 24); int intDataBytes = 0; byte[] bytBuffer = new byte[-1 + 1]; if (intFmtChunkLength == 16) { intDataBytes = System.BitConverter.ToInt32(bytHeader, 40); bytBuffer = new byte[intDataBytes + 44]; fs.Read(bytBuffer, 0, intDataBytes + 44); bytWaveData = new byte[intDataBytes]; Array.Copy(bytBuffer, 44, bytWaveData, 0, intDataBytes); } else if (intFmtChunkLength == 18) { intDataBytes = System.BitConverter.ToInt32(bytHeader, 42); bytBuffer = new byte[intDataBytes + 46]; fs.Read(bytBuffer, 0, intDataBytes + 46); bytWaveData = new byte[intDataBytes]; Array.Copy(bytBuffer, 46, bytWaveData, 0, intDataBytes); } fs.Close(); } catch { return false; } return true; }
public void Decrypt(string filename) { FileStream fsInput = new FileStream(filename, FileMode.Open, FileAccess.Read); FileStream fsOutput = new FileStream(filename + ".crypt", FileMode.Create, FileAccess.Write); AesCryptoServiceProvider Aes = new AesCryptoServiceProvider(); Aes.KeySize = 128; byte[] input = new byte[256]; int count = fsInput.Read(input, 0, 256); Aes.Key = _algorithm_asym.Decrypt(input, false); count = fsInput.Read(input, 0, 256); Aes.IV = _algorithm_asym.Decrypt(input, false); ICryptoTransform desencrypt = Aes.CreateDecryptor(); CryptoStream cryptostream = new CryptoStream(fsOutput, desencrypt, CryptoStreamMode.Write); byte[] bytearrayinput = new byte[fsInput.Length - 1]; fsInput.Read(bytearrayinput, 0, bytearrayinput.Length); cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length); fsInput.Close(); fsOutput.Close(); }
public void Open() { FirmwareSection i = 0; //Get the header and base page var stream = new FileStream(_fileName, FileMode.Open); var @base = GetSection(FirmwareSection.Base); stream.Read(_header, 0, _header.Length); stream.Read(@base, 0, @base.Length); //Read in all the sections while ((stream.Length - stream.Position) > 0x200) { var data = new byte[0x4000]; stream.Read(data, 0, data.Length); _sections.Add(i++, data); } //If we have a footer, read it in if ((stream.Length - stream.Position) == 0x200) { _footer = new byte[0x200]; stream.Read(_footer, 0, _footer.Length); } //All done stream.Close(); }
internal bool InitializeSizeAndName(FileStream fs) { this.Buffer = new byte[8]; int bytesRead = fs.Read(this.Buffer, 0, this.Buffer.Length); if (bytesRead < this.Buffer.Length) { return false; } this.Size = this.GetUInt(0); this.Name = this.GetString(4, 4); if (this.Size == 0) { this.Size = (ulong)(fs.Length - fs.Position); } if (this.Size == 1) { bytesRead = fs.Read(this.Buffer, 0, this.Buffer.Length); if (bytesRead < this.Buffer.Length) { return false; } this.Size = this.GetUInt64(0) - 8; } this.Position = ((ulong)fs.Position) + this.Size - 8; return true; }
private void frmRegHis_Load(object sender, EventArgs e) { try { string strRegAllInfo = File.ReadAllText(strRegKeyFile); PzCompression pzCom = PzCompressionHelper.getPzCompression(CompressionType.GZip); int nIdx = 0; byte[] byTmp; using (FileStream fsReg = new FileStream(strRegKeyFile, FileMode.Open, FileAccess.Read)) { while (true) { byTmp = new byte[4]; if (fsReg.Read(byTmp, 0, 4) < 1) break; int nLen = BitConverter.ToInt32(byTmp, 0); byTmp = new byte[nLen]; fsReg.Read(byTmp, 0, nLen); textBox1.Text += Encoding.Unicode.GetString(pzCom.DeCompress(byTmp)) + "\r\n"; nIdx++; } } label1.Text = string.Format("共授权完成{0}台机器", nIdx); } catch (Exception ex) { } }
/// <summary> /// 获取文件MD5 /// </summary> /// <param name="filePath"></param> /// <param name="type"></param> /// <returns></returns> public static string getMd5Hash(string filePath, int type) { string smd5 = filePath; try { using (FileStream t = new FileStream(filePath, FileMode.Open)) { int l = 1024; long l1 = t.Length / 3; long l2 = t.Length / 2; if (l1 < l) { l = (int)l1; } byte[] begin = new byte[l]; byte[] middle = new byte[l]; byte[] end = new byte[l]; t.Seek(0, SeekOrigin.Begin); t.Read(begin, 0, begin.Length); t.Seek(l2, SeekOrigin.Begin); t.Read(middle, 0, middle.Length); t.Seek(t.Length - end.Length, SeekOrigin.Begin); t.Read(end, 0, end.Length); string body = UnTo.byteToIntStr(begin) + UnTo.byteToIntStr(middle) + UnTo.byteToIntStr(end); return getMd5Hash(body); } } catch { return getMd5Hash(filePath); } }
/// <summary> /// Initializes a new instance of CImageFrame from a valid FileStream. /// </summary> /// <param name="file">The FileStream as it would be read by DarkEden.</param> public CEffectFrame(ref FileStream file) { byte[] _spriteid = new byte[2]; byte[] _x = new byte[2]; byte[] _y = new byte[2]; file.Read(_spriteid, 0, 2); file.Read(_x, 0, 2); file.Read(_y, 0, 2); this.SpriteID = BitConverter.ToUInt16(_spriteid, 0); this.X = BitConverter.ToInt16(_x, 0); this.Y = BitConverter.ToInt16(_y, 0); this.Light = (byte)file.ReadByte(); // Light and background boolean are stored in same byte. -> BLLLLLLL //file.ReadByte(); if ((this.Light & 0x80) > 0) { this.isBackground = true;// BitConverter.ToBoolean(new byte[] { (byte)((bgl & 0x01) >> 7) }, 0); this.Light &= 0x7F; //(byte)((bgl & 0x7F) << 1); } else this.isBackground = false; }
/// <summary> /// 判断两文件是否相同 /// </summary> /// <param name="fileA"></param> /// <param name="fileB"></param> /// <returns>true表示相同,false表示不相同</returns> public static bool FileEquals(string fileA, string fileB) { if (fileA == fileB) return true; using (FileStream fs1 = new FileStream(fileA, FileMode.Open, FileAccess.Read, FileShare.Read)) using (FileStream fs2 = new FileStream(fileB, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (fs1.Length != fs2.Length) { return false; } //每次读4K数据 const int oneRead = 4 * 1024; byte[] bin1 = new byte[oneRead]; byte[] bin2 = new byte[oneRead]; int readLen = fs1.Read(bin1, 0, oneRead); fs2.Read(bin2, 0, oneRead); while (readLen == oneRead) { if (ByteArrayEquals(bin1, bin2, oneRead)) { readLen = fs1.Read(bin1, 0, oneRead); fs2.Read(bin2, 0, oneRead); } else { return false; } } return ByteArrayEquals(bin1, bin2, readLen); } }
/// <summary> /// Detect MimeType from binary file by reading the first 256 bytes. /// </summary> /// <param name="filename">filename</param> /// <returns>mimetype or unknown/unknown</returns> public string GetMimeFromFile(string filename) { if (!File.Exists(filename)) throw new FileNotFoundException(String.Format("MimeTypeDetector: '{0}' not found!", filename)); byte[] buffer = new byte[256]; using (FileStream fs = new FileStream(filename, FileMode.Open)) { if (fs.Length >= 256) fs.Read(buffer, 0, 256); else fs.Read(buffer, 0, (int)fs.Length); } try { System.UInt32 mimetype; FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0); System.IntPtr mimeTypePtr = new IntPtr(mimetype); string mime = Marshal.PtrToStringUni(mimeTypePtr); Marshal.FreeCoTaskMem(mimeTypePtr); return mime; } catch (Exception e) { return "unknown/unknown"; } }
/// <summary> /// 分断读取数据 /// </summary> /// <param name="path"></param> private void ExportTxtByData(string path) { Response.Clear(); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment;filename=" + dlfile); Response.Flush(); Stream s = Response.OutputStream; using (FileStream fs = new FileStream(path + dlfile, FileMode.Open, FileAccess.Read)) { long fileLength = fs.Length; byte[] data = new byte[1024 * 1024]; int currentPosition = 0; while ((fs.Read(data, 0, data.Length) > 0)) { s.Write(data, 0, data.Length); currentPosition += data.Length; if ((fileLength - currentPosition) > data.Length) { Response.Flush(); continue; } else { data = new byte[fileLength - currentPosition]; fs.Read(data, 0, data.Length); s.Write(data, 0, data.Length); Response.Flush(); } } } s.Close(); }
public void Encrypt(string key) { var stream = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); // decido quanti byte di inizio file criptare // ovviamente devo tener conto della dimensione del file int headerSize = 254; if (headerSize > stream.Length) headerSize = (int)stream.Length; var firstBytes = new byte[headerSize]; stream.Read(firstBytes, 0, firstBytes.Length); // crittografa il primo blocco di N bytes var crypto = RijndaelService.EncryptBytes(firstBytes, key); // leggi tutto il contenuto restante byte[] bytes = new byte[stream.Length - firstBytes.Length]; stream.Read(bytes, 0, bytes.Length); stream.Close(); stream.Dispose(); // LA situazione ora è definita da // crypto: primi N bytes criptati // bytes: i restanti bytes del file, normali stream = new FileStream(Filename, FileMode.Create); // All'inizio del blocco specifica il numero dei byte adibiti all'header section stream.Write(BitConverter.GetBytes(crypto.Length), 0, sizeof(int)); stream.Write(crypto, 0, crypto.Length); stream.Write(bytes, 0, bytes.Length); stream.Close(); stream.Dispose(); }
public String Upload(UploadTask task) { FtpWebRequest ftpRequest = null; Stream ftpStream = null; int bufferSize = 8192; ftpRequest = (FtpWebRequest)FtpWebRequest.Create(Host + "/" + task.Remote); ftpRequest.Credentials = new NetworkCredential(Login, Password); ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.KeepAlive = true; ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; ftpStream = ftpRequest.GetRequestStream(); var localFileStream = new FileStream(task.Local, FileMode.Open); var byteBuffer = new byte[bufferSize]; int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); while (bytesSent != 0) { ftpStream.Write(byteBuffer, 0, bytesSent); bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize); } localFileStream.Close(); ftpStream.Close(); ftpRequest = null; return String.Format("{0}", task.Name); }
public override void ReadValue(FileStream dataStream) { // null base.ReadValue(dataStream); // data buffer byte[] buffer = new byte[sizeof(short)]; // Read our data into the buffer dataStream.Read(buffer, 0, sizeof(short)); // Check Endian if (BitConverter.IsLittleEndian) Array.Reverse(buffer); short first2 = BitConverter.ToInt16(buffer, 0); if (first2 < 0) throw new Exception("Bad VARCHAR read"); buffer = new byte[first2]; dataStream.Read(buffer, 0, first2); dataStream.Seek(this.size - first2 - sizeof(short), SeekOrigin.Current); Value = System.Text.ASCIIEncoding.ASCII.GetString(buffer); }
public static void UploadFile(string ftpHost, string username, string password, string filepathToUpload, string fileToWrite) { FtpClient chipbox = new FtpClient(); chipbox.Host = ftpHost; chipbox.Credentials = new NetworkCredential(username, password); Stream chipboxDosya = chipbox.OpenWrite(fileToWrite); FileStream dosya = new FileStream(filepathToUpload, FileMode.Open); try { int bufferSize = 8192; int readCount; byte[] buffer = new byte[bufferSize]; readCount = dosya.Read(buffer, 0, bufferSize); while (readCount > 0) { chipboxDosya.Write(buffer, 0, readCount); readCount = dosya.Read(buffer, 0, bufferSize); } } finally { dosya.Close(); chipboxDosya.Close(); } }
public static bool DecompressFileLZMA(string inFile, string outFile) { try { 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(); } catch (Exception) { return false; } return true; }
public static CompressedImage Load(string path, int DCTSize) { var result = new CompressedImage(); using (var sr = new FileStream(path, FileMode.Open)) { byte[] buffer = new byte[4]; sr.Read(buffer, 0, 4); result.Height = BitConverter.ToInt32(buffer, 0); sr.Read(buffer, 0, 4); result.Width = BitConverter.ToInt32(buffer, 0); sr.Read(buffer, 0, 4); result.CompressionLevel = BitConverter.ToInt32(buffer, 0); sr.Read(buffer, 0, 4); var blockSize = result.FrequencesPerBlock = BitConverter.ToInt32(buffer, 0); var blocksCount = result.Height * result.Width / (DCTSize * DCTSize); result.Frequences = new List<double>(blocksCount * result.FrequencesPerBlock); for (int blockNum = 0; blockNum < blocksCount; blockNum++) { for (int freqNum = 0; freqNum < blockSize; freqNum++) { sr.Read(buffer, 0, 2); result.Frequences.Add(BitConverter.ToInt16(buffer, 0)); } } } return result; }
public Matrix FileInitialization(string filename) { using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { var buff = new byte[255]; fs.Read(buff, 0, sizeof(int)); int n = BitConverter.ToInt32(buff, 0); fs.Read(buff, 0, sizeof(int)); int m = BitConverter.ToInt32(buff, 0); var matrix = new Matrix(n, m); for (var i = 0; i < n; i++) { for (var j = 0; j < m; j++) { fs.Read(buff, 0, sizeof (double)); matrix.Data[i][j] = BitConverter.ToDouble(buff, 0); } } return matrix; } }
public static void UploadToFTP(string filePath, string remotePath, string logOn, string password) { using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { string url = Path.Combine(remotePath, Path.GetFileName(filePath)); Uri uri = new Uri(url); FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(uri); ftp.Credentials = new NetworkCredential(logOn, password); ftp.KeepAlive = false; ftp.Method = WebRequestMethods.Ftp.UploadFile; ftp.UseBinary = true; ftp.ContentLength = fs.Length; ftp.Proxy = null; fs.Position = 0; int contentLen; int buffLength = 2048; byte[] buff = new byte[buffLength]; using (Stream strm = ftp.GetRequestStream()) { contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } } } }
public static DateTime GetAssemblyBuildTime(System.Reflection.Assembly assembly) { if (System.IO.File.Exists(assembly.Location)) { var buffer = new byte[Math.Max(Marshal.SizeOf(typeof(_IMAGE_FILE_HEADER)), 4)]; using (var fileStream = new FileStream(assembly.Location, FileMode.Open, FileAccess.Read)) { fileStream.Position = 0x3C; fileStream.Read(buffer, 0, 4); fileStream.Position = BitConverter.ToUInt32(buffer, 0); fileStream.Read(buffer, 0, 4); fileStream.Read(buffer, 0, buffer.Length); } var pinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); try { var coffHeader = (_IMAGE_FILE_HEADER)Marshal.PtrToStructure(pinnedBuffer.AddrOfPinnedObject(), typeof(_IMAGE_FILE_HEADER)); return TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1) + new TimeSpan(coffHeader.TimeDateStamp * TimeSpan.TicksPerSecond)); } finally { pinnedBuffer.Free(); } } else throw new Exception("Unable to read assembly"); }
public bool readArchiveFileHeader(FileStream fileHandle, ByteBuffer pMByteBuffer) { pMByteBuffer.clear (); fileHandle.Read(pMByteBuffer.dynBuff.buff, 0, 4); pMByteBuffer.length = 4; string magic = ""; pMByteBuffer.readMultiByte(ref magic, 4, Encoding.UTF8); if (magic != "asdf") // 检查 magic { return false; } pMByteBuffer.clear (); fileHandle.Read(pMByteBuffer.dynBuff.buff, 0, (int)calcArchiveHeaderSizeNoFileHeader() - 4); pMByteBuffer.length = calcArchiveHeaderSizeNoFileHeader() - 4; // 读取 endian pMByteBuffer.readUnsignedInt8(ref m_endian); pMByteBuffer.setEndian((Endian)m_endian); // 读取头部大小 pMByteBuffer.readUnsignedInt32(ref m_headerSize); // 读取版本 pMByteBuffer.readUnsignedInt32(ref m_version); // 读取文件数量 pMByteBuffer.readUnsignedInt32(ref m_fileCount); // 读取整个头 pMByteBuffer.clear (); fileHandle.Read(pMByteBuffer.dynBuff.buff, 0, (int)(m_headerSize - calcArchiveHeaderSizeNoFileHeader())); pMByteBuffer.length = m_headerSize - calcArchiveHeaderSizeNoFileHeader (); return true; }
/// <summary> /// Computes the CRC32 checksum of a file using the file path. /// The actual CRC32 algorithm is described in RFC 1952 /// (GZIP file format specification version 4.3), this is also /// the specification for the algorithm used in java.util.zip. /// </summary> /// <param name="filePath">the physical path of the file on the ESS</param> /// <returns>the string form of the calculated CRC32 checksum</returns> public static string ComputeCRC32(string filePath) { CRC_1952 crc = new CRC_1952(); FileStream fs = null; ulong csum = 0L; try { fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] buf = new byte[512]; int byteCount = fs.Read(buf, 0, 512); while (byteCount > 0) { csum = crc.updateCRC(csum, buf, byteCount); byteCount = fs.Read(buf, 0, 512); } fs.Close(); return csum.ToString("X"); } catch (IOException ex) { throw new IOException("Exception thrown computing CRC32 checksum using the file path", ex); } }
public byte[] CutToEnd(int position) { var size = Convert.ToInt32(_stream.Length - position); if (size == 0) { return(null); } var bytes = new byte[size]; SetPosition(position); _stream?.Read(bytes, 0, size); //_stream?.SetLength(position); return(bytes); }
protected void Page_Load(object sender, EventArgs e) { int fileID = Convert.ToInt32(Request.QueryString["ID"]); string type = Request.QueryString["type"]; string fileName = string.Empty; byte[] imageBytes = null; if (type == "training") { try { Training trainingHandler = new Training(); TrainingFormInfo formInfo = trainingHandler.getTrainingFormInfo(fileID); System.IO.FileStream file = new System.IO.FileStream(formInfo.FormPath, System.IO.FileMode.Open); System.IO.FileInfo fileInfo = new System.IO.FileInfo(formInfo.FormPath); fileName = formInfo.Description + fileInfo.Extension; int length = Convert.ToInt32(file.Length); imageBytes = new byte[length]; file.Read(imageBytes, 0, length); file.Close(); } catch (Exception ex) { Log.log(ex.Message + "\r\n" + ex.StackTrace, Log.Type.Exception); Response.ClearContent(); Response.Clear(); Response.Redirect("~/FileNotFound.html"); } } else { File file = new File(); FileInfo fileInfo = file.GetFileInfo(fileID); fileName = fileInfo.FileNameForDownload; imageBytes = file.GetFileByID(fileID); } Response.ClearContent(); Response.Clear(); Response.ContentType = "text/plain"; Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); Response.BinaryWrite(imageBytes); Response.Flush(); Response.End(); }
public static BlockExtension Load(System.IO.FileStream fs, Block b) { var data = new byte[14]; fs.Read(data, 0, data.Length); int materialID = System.BitConverter.ToInt32(data, 0); bool isNatural = data[4] == 1; var be = new BlockExtension(b, materialID, isNatural); be.existingPlanesMask = data[5]; be.fossilsVolume = System.BitConverter.ToSingle(data, 6); be.volume = System.BitConverter.ToSingle(data, 10); be.LoadPlanesData(fs); return(be); }
override public void Load(System.IO.FileStream fs, Plane sblock) { var data = new byte[STRUCTURE_SERIALIZER_LENGTH + 5]; fs.Read(data, 0, data.Length); Prepare(); modelRotation = data[2]; indestructible = (data[3] == 1); skinIndex = System.BitConverter.ToUInt32(data, 4); // mainResource = ResourceType.GetResourceTypeById(System.BitConverter.ToInt32(data, STRUCTURE_SERIALIZER_LENGTH)); resourceCount = data[STRUCTURE_SERIALIZER_LENGTH + 4]; // SetBasement(sblock, new PixelPosByte(data[0], data[1])); hp = System.BitConverter.ToSingle(data, 8); maxHp = System.BitConverter.ToSingle(data, 12); }
/// <summary> /// Encrypts a package (zip) file using a supplied password and returns /// an array to create an encryption information stream and a byte array /// of the encrypted package. /// </summary> /// <param name="filename">The package (zip) file to be encrypted</param> /// <param name="password">The password to decrypt the package</param> /// <param name="encryptionInfo">An array of bytes containing the encrption info</param> /// <param name="encryptedPackage">The encrpyted package</param> /// <returns></returns> public void EncryptPackage(string filename, string password, out byte[] encryptionInfo, out byte[] encryptedPackage) { if (!File.Exists(filename)) { throw new ArgumentException("Package file does not exist"); } // Grab the package contents and encrypt byte[] packageContents = null; using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite)) { packageContents = new byte[fs.Length]; fs.Read(packageContents, 0, packageContents.Length); } EncryptPackage(packageContents, password, out encryptionInfo, out encryptedPackage); }
byte [] GetBuffer( long bufferNum ) { byte [] result; if ( Buffers.TryGetValue( bufferNum, out result ) ) return result; result = new byte[ BufferSize ]; Buffers[ bufferNum ] = result; long pos = bufferNum << BufferShift; if ( BaseStream.Position != pos ) BaseStream.Position = pos; int i = 0; while ( i < BufferSize ) { int got = BaseStream.Read( result, i, BufferSize - i ); if ( got == 0 ) break; i += got; } return result; }
override public void Load(System.IO.FileStream fs, Plane sblock) { var data = new byte[STRUCTURE_SERIALIZER_LENGTH + 2]; fs.Read(data, 0, data.Length); Prepare(); modelRotation = data[2]; indestructible = (data[3] == 1); skinIndex = System.BitConverter.ToUInt32(data, 4); var ppos = new PixelPosByte(data[0], data[1]); hp = System.BitConverter.ToSingle(data, 8); maxHp = System.BitConverter.ToSingle(data, 12); SetData((Settlement.SettlementStructureType)data[STRUCTURE_SERIALIZER_LENGTH + 1], data[STRUCTURE_SERIALIZER_LENGTH], null); SetBasement(sblock, ppos); }
private void ProcessRequest(object o) { HttpListenerContext context = (HttpListenerContext)o; var request = context.Request; var response = context.Response; string url = context.Request.Url.AbsolutePath; RouteAction ra = routeManager.GetRoute(url); if (ra != null) { response.StatusCode = 200; object obj = Activator.CreateInstance(ra.Type); ra.Method.Invoke(obj, new object[] { context }); } else { // 静态资源 string filePath = Environment.CurrentDirectory + url; if (File.Exists(filePath)) { response.StatusCode = 200; string exeName = Path.GetExtension(filePath); response.ContentType = GetContentType(exeName); FileStream fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite); int byteLength = (int)fileStream.Length; byte[] fileBytes = new byte[byteLength]; fileStream.Read(fileBytes, 0, byteLength); fileStream.Close(); fileStream.Dispose(); response.ContentLength64 = byteLength; response.OutputStream.Write(fileBytes, 0, byteLength); response.OutputStream.Close(); } else { response.StatusCode = 404; response.ContentLength64 = 0; } } Logger.Info(string.Format("{0} {1} status:{2}", context.Request.HttpMethod, url, context.Response.StatusCode)); context.Response.Close(); }
private void InsertImageToDB() //вызывается только один раз при добалении картинок { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = @"INSERT INTO Images1 VALUES (@FileName, @ImageData)"; command.Parameters.Add("@FileName", SqlDbType.NVarChar, 50); command.Parameters.Add("@ImageData", SqlDbType.Image, 1000000); string[] filenames = new string[55]; string[] shortFileNames = new string[55]; for (int i = 0; i < 25; i++) { filenames[i] = $@"D:\images\{i + 1}.jpg"; shortFileNames[i] = $"{i + 1}.jpg"; } int j = 1; for (int i = 25; i < 48; i++, j++) { filenames[i] = $@"D:\images\wallpapers-nature-{j}.jpg"; shortFileNames[i] = $"wallpapers-nature-{j}.jpg"; } byte[] imageData; int k = 0; foreach (string filename in filenames) { if (k != 55) { using (System.IO.FileStream fs = new System.IO.FileStream(filename, FileMode.Open)) { imageData = new byte[fs.Length]; fs.Read(imageData, 0, imageData.Length); command.Parameters["@FileName"].Value = filename; command.Parameters["@ImageData"].Value = imageData; command.ExecuteNonQuery(); } k++; } } } }
override public void Load(System.IO.FileStream fs, Plane sblock) { base.Load(fs, sblock); artifacts = new Artifact[MAX_ARTIFACTS_COUNT]; var data = new byte[16]; fs.Read(data, 0, 16); int x = System.BitConverter.ToInt32(data, 0); if (x != -1) { artifacts[0] = Artifact.GetArtifactByID(x); } else { artifacts[0] = null; } x = System.BitConverter.ToInt32(data, 4); if (x != -1) { artifacts[1] = Artifact.GetArtifactByID(x); } else { artifacts[1] = null; } x = System.BitConverter.ToInt32(data, 8); if (x != -1) { artifacts[2] = Artifact.GetArtifactByID(x); } else { artifacts[2] = null; } x = System.BitConverter.ToInt32(data, 12); if (x != -1) { artifacts[3] = Artifact.GetArtifactByID(x); } else { artifacts[3] = null; } RecalculateAffection(); }
// 发送文件的线程函数 private void SendFileLoop() { while (SIGN_STREAMSETUP) { if (!SUSPEND_OF_SENDFILETHREAD) { sendfilestream = new FileStream(SENDFILEADDRESS, FileMode.Open, FileAccess.Read, FileShare.None); byte[] buffer = new byte[sendfilestream.Length]; string metaOfFile = "picture" + "//" + SENDFILENAME + "//" + sendfilestream.Length.ToString(); byte[] byte_metaOfFile = System.Text.Encoding.ASCII.GetBytes(metaOfFile); stream.Write(byte_metaOfFile, 0, byte_metaOfFile.Length); while (true) { if (!SUSPEND_OF_SENDFILETHREAD) { try { int length = sendfilestream.Read(buffer, 0, buffer.Length); if (length == 0) { sendfilestream.Close(); sendfilestream.Dispose(); // 发送文件完毕,进程挂起。 closeSendFile(); break; } stream.Write(buffer, 0, length); } catch (IOException ex) { MessageBox.Show(ex.ToString()); break; } } } } else { System.Threading.Thread.Sleep(200); } } }
public static Drawing.Image OpenImage(string fileName) { try { System.IO.FileStream fs = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); int byteLength = (int)fs.Length; byte[] fileBytes = new byte[byteLength]; fs.Read(fileBytes, 0, byteLength); fs.Close(); Drawing.Image image = Drawing.Image.FromStream(new MemoryStream(fileBytes)); return(image); } catch { return(null); } }
public void Load(System.IO.FileStream fs) { int LENGTH = 18; var data = new byte[LENGTH]; fs.Read(data, 0, LENGTH); richness = System.BitConverter.ToSingle(data, 0); danger = System.BitConverter.ToSingle(data, 4); mysteria = System.BitConverter.ToSingle(data, 8); friendliness = System.BitConverter.ToSingle(data, 12); path = (Path)data[16]; if (data[17] == 1) { int size = fs.ReadByte(); challengeArray = ChallengeField.Load(fs, size); } }
/// <summary> /// 返回Excel表中的首页名称(传入路径) /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static string GetSheetName(string filePath) { string sheetName = ""; System.IO.FileStream tmpStream = File.OpenRead(filePath); byte[] fileByte = new byte[tmpStream.Length]; tmpStream.Read(fileByte, 0, fileByte.Length); tmpStream.Close(); byte[] tmpByte = new byte[] { Convert.ToByte(11), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(11), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(0), Convert.ToByte(30), Convert.ToByte(16), Convert.ToByte(0), Convert.ToByte(0) }; int index = GetSheetIndex(fileByte, tmpByte); if (index > -1) { index += 16 + 12; System.Collections.ArrayList sheetNameList = new System.Collections.ArrayList(); for (int i = index; i < fileByte.Length - 1; i++) { byte temp = fileByte[i]; if (temp != Convert.ToByte(0)) { sheetNameList.Add(temp); } else { break; } } byte[] sheetNameByte = new byte[sheetNameList.Count]; for (int i = 0; i < sheetNameList.Count; i++) { sheetNameByte[i] = Convert.ToByte(sheetNameList[i]); } sheetName = System.Text.Encoding.Default.GetString(sheetNameByte); } if (sheetName == "") { sheetName = "Sheet1"; } return(sheetName); }
public ActionResult PostOpenAtChrome() { //string Filepath = @"C:\Users\WAN\source\repos\Wanlib\WanWebLib\SampleFile\測試下載用檔案.docx"; string Filepath = Server.MapPath("~/SampleFile/測試下載用檔案.docx"); string Folder = Server.UrlDecode("~/SampleFile"); string FileName = "測試下載用檔案.docx"; System.IO.FileStream fs = System.IO.File.OpenRead(Filepath); byte[] data = new byte[fs.Length]; int br = fs.Read(data, 0, data.Length); //return Redirect(Folder + "//" + FileName); return(File(data, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "阿捏.docx")); }
private static void LoadMd5FindFile() { if (m_LoadMd5FindFile) { return; } m_LoadMd5FindFile = true; string fileName = "Assets/md5Find.txt"; if (System.IO.File.Exists(fileName)) { System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); if (stream.Length > 0) { byte[] buf = new byte[stream.Length]; stream.Read(buf, 0, buf.Length); string s = System.Text.Encoding.ASCII.GetString(buf); List <string> lines = new List <string>(s.Split('\r')); for (int i = 0; i < lines.Count; ++i) { string line = lines[i].Trim(); if (string.IsNullOrEmpty(line)) { continue; } int idx = line.IndexOf('='); if (idx > 0) { string left = line.Substring(0, idx).Trim(); if (string.IsNullOrEmpty(left)) { continue; } string right = line.Substring(idx + 1).Trim(); if (string.IsNullOrEmpty(right)) { continue; } m_Md5FindMap.Add(left, right); } } } stream.Dispose(); stream.Close(); } }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Creating a Workbook object Workbook workbook = new Workbook(); // Creating a string variable to store the url of the logo/picture string logo_url = dataDir + "aspose-logo.jpg"; // Declaring a FileStream object FileStream inFile; // Declaring a byte array byte[] binaryData; // Creating the instance of the FileStream object to open the logo/picture in the stream inFile = new System.IO.FileStream(logo_url, System.IO.FileMode.Open, System.IO.FileAccess.Read); // Instantiating the byte array of FileStream object's size binaryData = new Byte[inFile.Length]; // Reads a block of bytes from the stream and writes data in a given buffer of byte array. long bytesRead = inFile.Read(binaryData, 0, (int)inFile.Length); // Creating a PageSetup object to get the page settings of the first worksheet of the workbook PageSetup pageSetup = workbook.Worksheets[0].PageSetup; // Setting the logo/picture in the central section of the page header pageSetup.SetHeaderPicture(1, binaryData); // Setting the script for the logo/picture pageSetup.SetHeader(1, "&G"); // Setting the Sheet's name in the right section of the page header with the script pageSetup.SetHeader(2, "&A"); // Saving the workbook workbook.Save(dataDir + "InsertImageInHeaderFooter_out.xls"); //Closing the FileStream object inFile.Close(); // ExEnd:1 }
/*private Complex[] prepare(String wavePath) * { * Complex[] data; * byte[] wave; * System.IO.FileStream WaveFile = System.IO.File.OpenRead(wavePath); * wave = new byte[WaveFile.Length]; * int defleng = (wave.Length - 44) / 4; * int leng = calcLenth(defleng); * N = leng; * data = new Complex[leng];//shifting the headers out of the PCM data; * WaveFile.Read(wave, 0, Convert.ToInt32(WaveFile.Length));//read the wave file into the wave variable * for (int i = 0; i < defleng; i++) * { * data[i] = (BitConverter.ToInt32(wave, 44 + i * 4)) / 4294967296.0; * } * * return data; * } */ private Complex[] fstprepare(String wavePath) { Complex[] data; byte[] wave; System.IO.FileStream WaveFile = System.IO.File.OpenRead(wavePath); wave = new byte[WaveFile.Length]; N = (wave.Length - 44) / 4; data = new Complex[N]; //shifting the headers out of the PCM data; WaveFile.Read(wave, 0, Convert.ToInt32(WaveFile.Length)); //read the wave file into the wave variable /***********Converting and PCM accounting***************/ for (int i = 0; i < N; i++) { data[i] = (Complex)(BitConverter.ToInt32(wave, 44 + i * 4)) / 4294967296.0; } return(data); }
/// <summary> /// Envia um arquivo no stream de rede /// </summary> /// <param name="pathSource">Caminho do arquivo a ser enviado</param> /// <param name="fileSize">Tamanho do arquivo</param> public void SendFile(string pathSource, long fileSize) { #if DEBUG Log.Framework.DebugFormat("Stream {0} irá enviar arquivo {1} de {2} bytes", this.GetHashCode(), pathSource, fileSize); #endif using (var reader = new System.IO.FileStream(pathSource, FileMode.Open)) { var totalSendedBytes = 0; try { while (fileSize > totalSendedBytes) { var bufferSize = this.GetBufferSize(fileSize, totalSendedBytes); var fileBuffer = new byte[bufferSize]; var sendedBytes = reader.Read(fileBuffer, 0, fileBuffer.Length); this.stream.Write(fileBuffer, 0, fileBuffer.Length); totalSendedBytes += sendedBytes; #if DEBUG Log.Framework.DebugFormat("Stream {0} enviou {1} de {2} bytes. Restam {3} bytes", this.GetHashCode(), sendedBytes, fileSize, fileSize - totalSendedBytes); #endif } } #if DEBUG catch (Exception exception) { Log.Application.Error(string.Format("Stream {0} não conseguiu enviar arquivo", this.GetHashCode()), exception); } #else catch { } #endif reader.Close(); } #if DEBUG Log.Application.DebugFormat("Stream {0} enviu o arquivo {1}", this.GetHashCode(), pathSource); #endif }
protected void btnContinue_Click(object sender, EventArgs e) { this.PhotoName = this.PhotoSaveNameCropped + LIB.Util.GetExtension(this.PhotoName); string PhotoFullPath = this._PhotoPath + this.PhotoName; wci1.Crop(PhotoFullPath); System.IO.FileStream fs = new System.IO.FileStream(Request.MapPath(Request.ApplicationPath + "/" + PhotoFullPath), FileMode.Open, FileAccess.ReadWrite); byte[] imgData = new byte[fs.Length]; fs.Read(imgData, 0, int.Parse(fs.Length.ToString())); fs.Close(); System.Drawing.Image img = System.Drawing.Image.FromStream(new MemoryStream(imgData)); int OrgW = img.Width; int OrgH = img.Height; int newW = 0; int newH = 0; if (OrgW > this._SizeW) { newW = this._SizeW; newH = (int)(OrgH / ((double)OrgW / this._SizeW)); Bitmap b = new Bitmap(newW, newH); Graphics g = Graphics.FromImage((System.Drawing.Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(img, 0, 0, newW, newH); g.Dispose(); img = (System.Drawing.Image)b; img.Save(Request.MapPath(PhotoFullPath), System.Drawing.Imaging.ImageFormat.Jpeg); } ImageHelper ImgHelper = new ImageHelper(); string SavePath = this.PhotoSaveNameThumb + LIB.Util.GetExtension(this.PhotoName); SavePath = Request.MapPath(this._PhotoPath + SavePath); ImgHelper.Crop(Request.MapPath(PhotoFullPath), SavePath, 0, 0, _SizeW, (int)COM.Enum.PhotoSizeH.SizeActivityPhotoSmallH); this.IsSaved = true; }
public void InitEveryThing() { this.BoneModel = this.BoneBLL.GetData(this.Model.IDCardNo, HealthHouseFactory.ID); if (this.BoneModel == null) { this.BoneModel = new HHBoneModel(); this.BoneModel.IDCardNo = this.Model.IDCardNo; } CSingleItem item = new CSingleItem { Name = "骨密度", Usual = this.rdBone, Unusual = this.rdBoneEx, Info = this.txtResultEx }; this.Bone = item; this.Bone.TransInfo(this.BoneModel.Result, this.BoneModel.ResultEx); if (!string.IsNullOrEmpty(this.BoneModel.ImgPath) && File.Exists(this.BoneModel.ImgPath)) { //读取文件流 System.IO.FileStream fs = new System.IO.FileStream(this.BoneModel.ImgPath, FileMode.Open, FileAccess.Read); int byteLength = (int)fs.Length; byte[] fileBytes = new byte[byteLength]; fs.Read(fileBytes, 0, byteLength); //文件流关閉,文件解除锁定 fs.Close(); Image image = Image.FromStream(new MemoryStream(fileBytes)); pboxBShow.Image = image; //Image img = System.Drawing.Image.FromFile(this.BoneModel.ImgPath); //Image bmp = new System.Drawing.Bitmap(img); //img.Dispose(); //pboxBShow.Image = bmp; } else { btnPrint.Visible = false; } this.EveryThingIsOk = true; }
public void OnClickLoadAndSetTextureButton() { string filePathAndName = Application.persistentDataPath + "/" + SaveFileName; // https://qiita.com/r-ngtm/items/6cff25643a1a6ba82a6c // ここ参考にした //ファイルを開く System.IO.FileStream fs = new System.IO.FileStream( filePathAndName, System.IO.FileMode.Open, System.IO.FileAccess.Read ); //ファイルを読み込むバイト型配列を作成する byte[] bs = new byte[fs.Length]; //ファイルの内容をすべて読み込む fs.Read(bs, 0, bs.Length); //閉じる fs.Close(); int pos = 16; // 16バイトから開始 int width = 0; for (int i = 0; i < 4; i++) { width = width * 256 + bs[pos++]; } int height = 0; for (int i = 0; i < 4; i++) { height = height * 256 + bs[pos++]; } TakeTexture = new Texture2D(width, height); TakeTexture.LoadImage(bs); Sprite sprite = Sprite.Create(TakeTexture, new Rect(0, 0, width, height), Vector2.zero); TestImage.sprite = sprite; }
/// <summary> /// 把一个文件存入数据库 /// </summary> public int WriteFile(string FilePath, string SqlString, string ParamName, bool Add) { if (!System.IO.File.Exists(FilePath)) { return(0); } //存储和读取Access数据库的OLE对象一般是转换成byte数组进行处理 System.IO.FileStream stream = new System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] bData; int offset = 0; if (Add) { offset = 10; bData = new byte[stream.Length + 10]; bData[0] = bData[1] = bData[2] = (byte)3; bData[3] = bData[4] = bData[5] = (byte)6; bData[6] = bData[7] = bData[8] = (byte)9; bData[9] = (byte)0; } else { bData = new byte[stream.Length]; } stream.Read(bData, offset, (int)stream.Length); OleDbCommand cmd = new OleDbCommand(SqlString, this.cn); cmd.Parameters.Add(new OleDbParameter(ParamName, bData)); if (cn.State != ConnectionState.Open) { cn.Open(); } cmd.CommandTimeout = 500; int a = cmd.ExecuteNonQuery(); cmd.Dispose(); stream.Dispose(); return(a); }
/// <summary> /// 压缩文件 /// </summary> /// <param name="FileToZip">待压缩的文件</param> /// <param name="ZipedFile">压缩后的文件</param> /// <param name="password">压缩密码</param> private static void ZipFile(string FileToZip, string ZipedFile, string password) //如果文件没有找到,则报错 { if (!System.IO.File.Exists(FileToZip)) { throw new System.IO.FileNotFoundException("文件 " + FileToZip + "不存在!"); } //取得待压缩文件流 System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read); //创建压缩后的文件 System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile); //创建新的ZIP输出流 ZipOutputStream ZipStream = new ZipOutputStream(ZipFile); // 每一个被压缩的文件都用ZipEntry表示,需要为每一个压缩后的文件设置名称 ZipEntry ZipEntry = new ZipEntry("ZippedFile"); //设置每一个ZipEntry对象 ZipStream.PutNextEntry(ZipEntry); // 为后续的 DEFLATED 条目设置压缩级别。 0 -9 ZipStream.SetLevel(6); //设置解压密码 ZipStream.Password = password; //每次写入1024个字节 byte[] buffer = new byte[1024]; int size = 0; //已写入压缩流的字节数 try { //如果没有写入完成 while (size < StreamToZip.Length) { //将文件内容写入buffer int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length); //将字节写入压缩流 ZipStream.Write(buffer, 0, sizeRead); size += sizeRead; } } catch (System.Exception ex) { throw ex; } //完成写入 ZIP 输出流的内容,无需关闭底层流。 ZipStream.Finish(); //关闭 ZIP 输出流和正在过滤的流。 ZipStream.Close(); //关闭文件流 StreamToZip.Close(); }
public byte[] getSouceFileContent(string strSource) { byte[] binaryData; try { System.IO.FileStream inFile = new System.IO.FileStream(strSource, System.IO.FileMode.Open, System.IO.FileAccess.Read); binaryData = new Byte[inFile.Length]; long bytesRead = inFile.Read(binaryData, 0, (int)inFile.Length); inFile.Close(); } catch (System.Exception exp) { throw new System.Exception(exp.Message, exp); } return(binaryData); }
/// <summary> /// 读取指定文件 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static string ReadFile(string fileName) { System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate); byte[] buff = new byte[fs.Length]; fs.Read(buff, 0, buff.Length); fs.Flush(); fs.Close(); fs.Dispose(); fs = null; if (buff != null && buff.Length > 3 && buff[0] == 0xEF && buff[1] == 0xBB && buff[2] == 0xBF) { return(new UTF8Encoding(false).GetString(buff, 3, buff.Length - 3)); } return(Encoding.UTF8.GetString(buff)); }
public static string ReadTextFile(FileInfo file, Encoding encoding) { // Validate parameter(s). ThrowHelper.ArgumentNull((file == null), nameof(file)); ThrowHelper.ArgumentNull((encoding == null), nameof(encoding)); System.IO.FileStream stream = file.Open(FileMode.Open, FileAccess.Read); int length = Convert.ToInt32(file.Length); byte[] buffer = new byte[length]; stream.Read(buffer, 0, length); stream.Close(); // Convert to text string text = encoding.GetString(buffer); return(text); }
public static string ImageToBase64String(string ImagePath)//需要public stitic方便外部调用 { if (ImagePath == "") { return(""); } byte[] buffer = new byte[0]; System.IO.FileInfo fi = new System.IO.FileInfo(ImagePath); long len = fi.Length; System.IO.FileStream fs = new System.IO.FileStream(ImagePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); buffer = new byte[len]; fs.Read(buffer, 0, (int)len); fs.Close(); return(Convert.ToBase64String(buffer)); }
private byte[] GetFile(string s) { try { System.IO.FileStream fs = System.IO.File.OpenRead(s); byte[] data = new byte[fs.Length]; int br = fs.Read(data, 0, data.Length); if (br != fs.Length) { throw new System.IO.IOException(s); } return(data); } catch (Exception exception) { return(null); } }
public byte[] GetContent() { if (!Exists()) { return(null); } System.IO.FileStream fs = System.IO.File.OpenRead(FilePathAndName); byte[] data = new byte[fs.Length]; int br = fs.Read(data, 0, data.Length); if (br != fs.Length) { throw new System.IO.IOException(FilePathAndName); } fs.Close(); return(data); }