/// <summary> /// Alloc new segment /// Include reserve segment and normal segment /// </summary> /// <returns></returns> private int AllocNewSegment() { if (CurSegment < _LastReserveSegment && _LastUsedReserveSegment > 0 && _LastUsedReserveSegment < _LastReserveSegment) { //Alloc reserve segment _LastUsedReserveSegment++; _CurSegment = _LastUsedReserveSegment; } else if (_LastUsedSegment > 0 && _LastUsedSegment < LastSegment) { _LastUsedSegment++; _CurSegment = _LastUsedSegment; } else { if (AutoIncreaseBytes <= 0) { throw new System.IO.IOException("File full because AutoIncreaseBytes == 0"); } _LastUsedSegment = LastSegment + 1; _CurSegment = _LastUsedSegment; _FileStream.SetLength((LastSegment + 1) * SegmentSize + AutoIncreaseBytes); _LastSegment += AutoIncreaseBytes / SegmentSize; } return(CurSegment); }
public void Truncate(long Position) { using (System.IO.FileStream Stream = new System.IO.FileStream(this.PathNameFile(), System.IO.FileMode.Truncate)) { Stream.SetLength(Position); } }
public void on_Click(object sender, DirectEventArgs e) { if (Session["service"] != null && Session["user"] != null) { //String name = ComboBox1.SelectedItem.Value; string path = this.FileUploadField1.FileName; path = Server.MapPath(path); User u = Session["user"] as User; Uri postUri = new Uri(PicasaQuery.CreatePicasaUri("diegoturciostc", "5680246730142935889")); System.IO.Stream fileInfo = this.FileUploadField1.PostedFile.InputStream; int buffer = 1024 * 1024; System.IO.FileStream filestream = null;//new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); filestream = System.IO.File.Create(path); filestream.SetLength(fileInfo.Length); int bytesRead = -1; byte[] bytes = new byte[buffer]; while ((bytesRead = fileInfo.Read(bytes, 0, buffer)) > 0) { filestream.Write(bytes, 0, bytesRead); } PicasaService tmp = Session["service"] as PicasaService; PicasaEntry entry = (PicasaEntry)tmp.Insert(postUri, filestream, "image/jpeg", path); filestream.Close(); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } }
private void button_export_Click(object sender, EventArgs e) { DataTable dt = dataGridView1.DataSource as DataTable; if (dt == null) { MessageBox.Show("你脑子秀逗了?"); return; } string outputText = ""; foreach (DataRow r in dt.Rows) { for (int i = 0; i < r.ItemArray.Length; i++) { outputText += r[i] as string + ","; } outputText = outputText.Substring(0, outputText.Length - 1) + "\r\n"; } System.IO.FileStream fs = new System.IO.FileStream("./yoyohate.csv", System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.StreamWriter sw = new System.IO.StreamWriter(fs); fs.SetLength(0); sw.Write(outputText); sw.Close(); fs.Close(); MessageBox.Show("yoyo会恨你的,去打开yoyohate.csv吧"); }
internal void Create(List <Data.Field> fields) { List <Data.Field> tmpFields = new List <Hubble.Core.Data.Field>(); foreach (Data.Field field in fields) { if (field.IndexType != Hubble.Core.Data.Field.Index.None) { tmpFields.Add(field); } } tmpFields.Sort(new TabCompare()); PayloadFileHead head = new PayloadFileHead(); head.Build(tmpFields); if (System.IO.File.Exists(_FileName)) { System.IO.File.Delete(_FileName); } using (System.IO.FileStream fs = new System.IO.FileStream(_FileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite)) { Hubble.Framework.Serialization.BinSerialization.SerializeBinary(head, fs); fs.SetLength(HeadLength); } }
/// <summary> /// Saves this instance. /// </summary> public void Save() { System.Xml.Serialization.XmlSerializer sz = new System.Xml.Serialization.XmlSerializer(typeof(PreferredSiteList)); using (System.IO.FileStream fs = System.IO.File.Open(AppSettingFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.None)) { fs.SetLength(0); sz.Serialize(fs, this); } }
public DBase3(System.String name, int numfields) { InitBlock(); recordSize = 1; db = SupportClass.RandomAccessFileSupport.CreateRandomAccessFile(name, "rw"); //UPGRADE_TODO: Method 'java.io.RandomAccessFile.setLength' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1095"' db.SetLength(0); fields = new FieldDescriptor[numfields]; hdrSize = (short)(33 + 32 * fields.Length); }
/// <summary> Description of the Method /// /// </summary> /// <param name="recordNumber"> Description of the Parameter /// </param> /// <exception cref=""> IOException Description of the Exception /// </exception> public virtual void remove(int recordNumber) { long size = file.Length; long idx = (long)(recordNumber + 1) * (long)recordSize + HEADER_SIZE; if (recordNumber == count - 1) { //UPGRADE_TODO: Method 'java.io.RandomAccessFile.setLength' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1095"' file.SetLength(idx); } else { sbyte[] bigBuffer = new sbyte[(int)(size - idx)]; file.Seek(idx, System.IO.SeekOrigin.Begin); SupportClass.ReadInput(file, ref bigBuffer, 0, bigBuffer.Length); file.Seek(idx - recordSize, System.IO.SeekOrigin.Begin); SupportClass.RandomAccessFileSupport.WriteRandomFile(bigBuffer, file); //UPGRADE_TODO: Method 'java.io.RandomAccessFile.setLength' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1095"' file.SetLength(size - recordSize); } }
protected void Reset() { Debug.Assert(IsConnected); lock (m_rwLock) { Header.Reset(); m_dataFile.SetLength(0); Header.Store(m_writer); TableResetted?.Invoke(); } }
public void Save() { string constructedString = s_settings.Aggregate("", (str, di) => str + (di.Key + ":" + di.Value + Environment.NewLine)); if (constructedString != "") { constructedString = constructedString.Substring(0, constructedString.LastIndexOf(Environment.NewLine, StringComparison.Ordinal)); } s_file.SetLength(constructedString.Length); s_file.Position = 0; byte[] bytesToWrite = System.Text.Encoding.ASCII.GetBytes(constructedString); s_file.Write(bytesToWrite, 0, bytesToWrite.Length); s_file.Flush(); }
public static string CreateVirtualDisk(int iSize) { string strBaseDirectory = @"/volumes/"; string strFileName = System.Guid.NewGuid().ToString().Replace("-", "") + ".dsk"; string strFileNameAndPath = System.IO.Path.Combine(strBaseDirectory, strFileName); using (var fs = new System.IO.FileStream(strFileNameAndPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { fs.SetLength(iSize); } // End Using fs return(strFileNameAndPath); } // End Function CreateVirtualDisk
public static void Save() { try { var fs = new System.IO.FileStream("model.dat", System.IO.FileMode.OpenOrCreate); //List<ULTypeInfo> type_list = new List<ULTypeInfo>(TypeNames.Values); MongoDB.Bson.Serialization.BsonSerializer.Serialize(new MongoDB.Bson.IO.BsonBinaryWriter(fs), TypeNames); fs.SetLength(fs.Position); fs.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } }
public static void SaveCollection(Person[] People) { FileStream.SetLength(People.Length * Person.MaxObjectSize); FileStream.Position = 0; foreach (Person PersonToWrite in People) { // call serialise to get bytes byte[] OutputBytes = PersonToWrite.Serialise(); // write the output buffer // note: this will always be the same size as each variable should // append spaces until its max size is reached FileStream.Write(OutputBytes, 0, OutputBytes.Length); } }
public void CleanFile(out bool ok) { try { Console.WriteLine("debugger cleanfile"); fstream.SetLength(0); ok = true; Console.WriteLine("debugger cleanfile2"); } catch (Exception e) { System.Console.Error.WriteLine(e); ok = false; } }
public static void Save(this Report report, string path) { //TODO 3tk workaround hence can't serialize anonymous classes hidden in PropertyDataField<T,K> - //should find way to serialize anonymous types report.Parameters.Clear(); report.DataFields.Clear(); using (System.IO.FileStream file = System.IO.File.OpenWrite(path)) { var serializedProject = JsonConvert.SerializeObject(report, Formatting.None, new JsonSerializerSettings { ContractResolver = new MonoReportsContractResolver(), TypeNameHandling = TypeNameHandling.Objects } ); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(serializedProject); file.SetLength(bytes.Length); file.Write(bytes, 0, bytes.Length); file.Close(); } }
/// <summary> /// Writes the index to the file starting at the FileStream's current Position. The file length will be shortened if necessary to ensure that the end of the index is the end of the file. /// </summary> /// <param name="fs"></param> internal void WriteToStream(System.IO.FileStream fs) { Offset = fs.Position; fs.Write(ByteConverter.GetBytes(magicShortValue), 0, 2); foreach (KeyValuePair <string, BundledFileInfo> kvp in myIndex) { byte[] fileNameBytes = ByteConverter.GetBytes(kvp.Value.Name); fs.Write(ByteConverter.GetBytes((short)fileNameBytes.Length), 0, 2); fs.Write(fileNameBytes, 0, fileNameBytes.Length); fs.Write(ByteConverter.GetBytes(kvp.Value.Position), 0, 8); } fs.Write(ByteConverter.GetBytes(Offset), 0, 8); long position = fs.Position; if (position != fs.Length) { fs.SetLength(position); } fs.Flush(true); }
static int _m_SetLength(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.IO.FileStream gen_to_be_invoked = (System.IO.FileStream)translator.FastGetCSObj(L, 1); { long _value = LuaAPI.lua_toint64(L, 2); gen_to_be_invoked.SetLength(_value); return(0); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } }
private System.IO.FileStream InitFile(string fileName, int segmentSize, int reserverSegmentLen, bool createNew) { System.IO.FileStream fs; if (!System.IO.File.Exists(fileName)) { createNew = true; } if (createNew) { if (System.IO.File.Exists(fileName)) { System.IO.File.Delete(fileName); } fs = new System.IO.FileStream(fileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite); try { fs.SetLength(segmentSize * reserverSegmentLen); } catch (Exception e) { Close(); throw e; } } else { fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite); } return(fs); }
private void writeLua(List <string> classes, List <string> stats) { foreach (string element in classes) { //Player Table System.IO.File.WriteAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "Player = {"); foreach (string elementS in stats) { System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "\n\t" + elementS + " = 0,"); } //Removes the last comma System.IO.FileStream fs = new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite); fs.SetLength(fs.Length - 1); fs.Close(); System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "\n}\n\n"); //Adversary Table System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "Adversary = {"); foreach (string elementS in stats) { System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "\n\t" + elementS + " = 0,"); } //Removes the last comma fs = new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite); fs.SetLength(fs.Length - 1); fs.Close(); System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "\n}\n\n"); //Set Adversary Function System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "function setAdversary ("); foreach (string elementS in stats) { System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", elementS + ", "); } fs = new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite); fs.SetLength(fs.Length - 2); fs.Close(); System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", ")"); foreach (string elementS in stats) { System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "\n\tAdversary." + elementS + " = " + elementS); } System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "\nend\n\n"); foreach (string elementS in stats) { System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "function stat" + elementS + "(lvl)\n\tPlayer." + elementS + " = (3 * lvl)\n\treturn Player." + elementS + "\nend\n\n"); } System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/" + element + ".lua", "function actionAttack ()\n\treturn (2 * Player." + stats[0] + ") - Adversary." + stats[1] + "\nend"); } /* * System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/class.lua", "Player = {\n--Loop here\n\t" + element + "= 0,\n\t" + element + "= 0\n--End loop\n}\n"); * System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/class.lua", "Adversary = {\n--Loop here\n\t" + element + "= 0, \n\t" + element + " = 0\n--End loop\n}\n\n--Loop here\n'stat'base = 0;\n--End loop"); * * System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/class.lua", "function setAdversary (element[0], element[1])\n--Look into getting those the same way we get Player stats, maybe through something like dofile()\n--This would allow for greater number of stats\n\tAdversary.attack = attack\n\tAdversary.magic = magic\n\tAdversary.defence = defence\nend"); * * foreach (string element in classes) * { * System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/class.lua", "--Loop here\nfunction stat element (lvl)\n\tPlayer.element = elementBase + (3 * lvl)\n\treturn Player.element\nend\n--End loop"); * } * System.IO.File.AppendAllText(@System.IO.Directory.GetCurrentDirectory() + "/Game/class.lua", "function actionAttack ()\n\treturn (2 * Player.attack) - Adversary.defence\nend"); */ }
private void btnFix_Click(object sender, EventArgs e) { System.IO.FileStream stream = null; try { stream = new System.IO.FileStream(txtFile.Text, System.IO.FileMode.Open); System.IO.BinaryReader fileR = new System.IO.BinaryReader(stream); System.IO.BinaryWriter fileW = new System.IO.BinaryWriter(stream); ushort offset = ushort.Parse(txtOffset.Text, System.Globalization.NumberStyles.HexNumber); ushort size = ushort.Parse(txtSize.Text, System.Globalization.NumberStyles.HexNumber); ushort vtOffset = FixOffsetAt(fileR, fileW, 0x02, offset, size); //v-table offset ushort refOffset = FixOffsetAt(fileR, fileW, 0x06, offset, size); //references to offsets to fix in-game FixOffsetAt(fileR, fileW, 0x10, offset, size); //spawn function stream.Position = 0x04; ushort vtCount = fileR.ReadUInt16(); stream.Position = 0x08; ushort refCount = fileR.ReadUInt16(); stream.Position = vtOffset; for (ushort i = 0; i < vtCount; ++i) { uint funcPtr = fileR.ReadUInt32(); if ((funcPtr & 0xF0000000) != 0) { FixOffsetAt(fileR, fileW, (ushort)(stream.Position - 4), offset, size); stream.Position += 2; } } for (ushort i = 0; i < refCount; ++i) { stream.Position = refOffset + 2 * i; ushort oldVarOffset = fileR.ReadUInt16(); ushort varOffset = FixOffsetAt(fileR, fileW, (ushort)(refOffset + 2 * i), offset, size); //remove references whose referencees (notice: 2 e's in a row) //have been deleted if (varOffset < oldVarOffset && varOffset < offset || varOffset > stream.Length) { stream.Position = refOffset + 2 * i; fileW.Write((ushort)0x0000); } else { stream.Position = varOffset; uint varPtr = fileR.ReadUInt32(); if ((varPtr & 0xF0000000) == 0) { FixOffsetAt(fileR, fileW, varOffset, offset, size); } } } ushort j = 0; for (ushort i = 0; i < refCount; ++i, ++j) { stream.Position = refOffset + 2 * i; ushort varOffset = fileR.ReadUInt16(); if (varOffset == 0x0000) { --j; continue; } stream.Position = refOffset + 2 * j; fileW.Write(varOffset); } stream.Position = 0x08; fileW.Write(j); //new reference count stream.SetLength(refOffset + 2 * j); stream.Close(); MessageBox.Show("Operation complete! Now go fix the offsets for loading constants.", "Good!", MessageBoxButtons.OK); } catch (Exception ex) { if (stream != null) { stream.Close(); } new ExceptionMessageBox("Error", ex).ShowDialog(); return; } }
public override void SetLength(long length) { file.SetLength(length); }
internal PayloadProvider Open(Field docIdReplaceField, List <Data.Field> fields, int payloadLength, out int lastDocId) { lastDocId = -1; List <Data.Field> tmpFields = new List <Hubble.Core.Data.Field>(); PayloadProvider docPayload = new PayloadProvider(docIdReplaceField); long truncateLength = 0; int rankTab = -1; foreach (Data.Field field in fields) { if (field.IndexType != Hubble.Core.Data.Field.Index.None) { tmpFields.Add(field); } if (field.Name.Equals("Rank", StringComparison.CurrentCultureIgnoreCase)) { if (field.IndexType == Field.Index.Untokenized && field.DataType == DataType.Int) { rankTab = field.TabIndex; } } } tmpFields.Sort(new TabCompare()); PayloadFileHead head = new PayloadFileHead(); head.Build(tmpFields); if (_StoreLength <= 0) { _StoreLength = payloadLength * 4 + sizeof(int); } using (System.IO.FileStream fs = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { object obj; Hubble.Framework.Serialization.BinSerialization.DeserializeBinary(fs, out obj); PayloadFileHead fileHead = (PayloadFileHead)obj; if (fileHead.IsBigEndian != head.IsBigEndian) { throw new Data.DataException(string.Format("Index file IsBigEndian = {0} but current system IsBigEndian = {1}. Can't load payload file", fileHead.IsBigEndian, head.IsBigEndian)); } if ((fileHead.Version[0] <= 0 && fileHead.Version[1] < 8) || (fileHead.Version[0] <= 0 && fileHead.Version[1] == 8 && fileHead.Version[2] == 0 && fileHead.Version[3] < 4)) { throw new Data.DataException("Index file version is less than V0.8.0.4, you have to rebuild the index"); } for (int i = 0; i < head.FieldMD5.Length; i++) { if (head.FieldMD5[i] != fileHead.FieldMD5[i]) { throw new Data.DataException(string.Format("Payload file name: {0} does not match with the table", _FileName)); } } fs.Seek(HeadLength, System.IO.SeekOrigin.Begin); if (payloadLength > 0 && InsertProtect.InsertProtectInfo == null) { lastDocId = FastLoad(docPayload, fs, rankTab); _LastStoredId = lastDocId; _DocumentsCount = (int)((fs.Length - HeadLength) / _StoreLength); GC.Collect(); return(docPayload); } bool breakForProctect = false; while (fs.Position < fs.Length) { if (payloadLength == 0 && InsertProtect.InsertProtectInfo != null) { //Exit exception last time lastDocId = InsertProtect.InsertProtectInfo.LastDocId; _LastStoredId = lastDocId; _DocumentsCount = InsertProtect.InsertProtectInfo.DocumentsCount; break; } int fileIndex = (int)((fs.Position - HeadLength) / _StoreLength); byte[] buf = new byte[sizeof(int)]; fs.Read(buf, 0, buf.Length); int docidInFile = (int)BitConverter.ToInt32(buf, 0); if (docidInFile < lastDocId) { throw new Data.DataException(string.Format("docid = {0} < last docid ={1}", docidInFile, lastDocId)); } lastDocId = docidInFile; _LastStoredId = lastDocId; if (InsertProtect.InsertProtectInfo != null) { if (lastDocId == InsertProtect.InsertProtectInfo.LastDocId) { breakForProctect = true; } //Exit exception last time if (lastDocId > InsertProtect.InsertProtectInfo.LastDocId) { lastDocId = InsertProtect.InsertProtectInfo.LastDocId; _LastStoredId = lastDocId; truncateLength = fs.Position - sizeof(int); break; } } if (payloadLength == 0) { buf = new byte[sizeof(int)]; fs.Read(buf, 0, buf.Length); _DocumentsCount = (int)BitConverter.ToInt32(buf, 0); return(docPayload); } byte[] byteData = new byte[payloadLength * 4]; fs.Read(byteData, 0, byteData.Length); Data.Payload payload = new Hubble.Core.Data.Payload(payloadLength); payload.CopyFrom(byteData); payload.FileIndex = fileIndex; if (payloadLength > 0) { docPayload.Add(lastDocId, payload); _DocumentsCount++; } if (breakForProctect) { truncateLength = fs.Position; break; } } GC.Collect(); } if (InsertProtect.InsertProtectInfo != null) { //Exit exception last time if (InsertProtect.InsertProtectInfo.LastDocId < 0) { //No Data lastDocId = -1; _LastStoredId = lastDocId; using (System.IO.FileStream fs = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Write)) { fs.SetLength(HeadLength); } } else { //Have data if (payloadLength == 0) { using (System.IO.FileStream fs = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Write)) { //Seek to end of head fs.Seek(HeadLength, System.IO.SeekOrigin.Begin); //Write last doc id byte[] buf = BitConverter.GetBytes(InsertProtect.InsertProtectInfo.LastDocId); fs.Write(buf, 0, buf.Length); //Write documents count buf = BitConverter.GetBytes(InsertProtect.InsertProtectInfo.DocumentsCount); fs.Write(buf, 0, buf.Length); } } else { using (System.IO.FileStream fs = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Write)) { if (truncateLength > 0 && truncateLength < fs.Length) { fs.SetLength(truncateLength); } } } } } return(docPayload); }
public override void SetLength(long value) { InternalFileStream.SetLength(value); }
private void createfilebutton_Click(object sender, EventArgs e) { if (running) { abort = true; return; } if (string.IsNullOrEmpty(sizecombo.Text) && maxsizebutton.Checked == false) { MessageBox.Show("Please enter a valid size for the file"); return; } if (System.IO.Directory.Exists(filelocation.Text) == false) { MessageBox.Show("Please enter a valid directory"); return; } initData(datarandom.Checked); String hard = "dummyfile"; int counter = 0; while (System.IO.File.Exists(hard + counter.ToString() + ".txt")) { counter++; } System.IO.Directory.SetCurrentDirectory(filelocation.Text); System.IO.FileStream FS = null; try { FS = System.IO.File.Create(hard + counter.ToString() + ".txt"); } catch (Exception ex) { MessageBox.Show("An error occured creating the file:" + ex.ToString()); return; } toggleControls(); abort = false; int size = 0; ulong kbsize = 0; if (maxsizebutton.Checked == false) { size = int.Parse(sizecombo.Text); kbsize = (ulong)size; if (mbswitch.Checked || gbswitch.Checked) { kbsize *= 1024; } if (gbswitch.Checked) { kbsize *= 1024; } } else { try { String current = System.IO.Directory.GetCurrentDirectory(); ulong by1, by2 = 0; ulong freebytes = 0; GetDiskFreeSpaceEx(current, out by1, out by2, out freebytes); kbsize = freebytes /= 1024; //leave 1 free mb kbsize -= 1024; } catch { MessageBox.Show("Error creating max size file"); return; } } lengthmax.Text = kbsize.ToString(); try { if (datarandom.Checked) { System.IO.StreamWriter SW = new System.IO.StreamWriter(FS); ulong a = 0; while (a < kbsize) { if (kbsize >= 1024) { SW.Write(mb); a += 1024; progress(a, kbsize); } else { SW.Write(kb); a++; progress(a, kbsize); } if (abort) { toggleControls(); SW.Close(); FS.Close(); return; } } SW.Close(); } else { //in bytes FS.SetLength((long)kbsize * 1024); } } //most likely no room left catch (Exception e1) { MessageBox.Show("Error:" + e1.ToString()); } FS.Close(); toggleControls(); }
public override void SetLength(long length) { System.IO.FileStream fs = (System.IO.FileStream)file.BaseStream; fs.SetLength(length); }
private static void retrylogthreadproc() { #if DEBUG //System.Threading.Thread.Sleep(1000 * 8); #endif for (; ; ) { try { using (System.IO.FileStream fs = new System.IO.FileStream(logFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { _retryloginitpos = fs.Length; } } catch (System.IO.FileNotFoundException) { _retryloginitpos = 0; } catch { System.Threading.Thread.Sleep(1000 * 1); continue; } break; } StringBuilder sbbuf = new StringBuilder(0x400); for (; ; ) { int retrylogbufLength; bool mystop; lock (retrylogbuf) { retrylogbufLength = retrylogbuf.Length; mystop = retrylogstop; } if (_retrylogcharpos < retrylogbufLength) { try { if (_retrylogcharpos < 0) // Need to rewrite all? { using (System.IO.FileStream fs = new System.IO.FileStream(logFilePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read)) { long fsLength = fs.Length; if (0 == fsLength) { // File might have been deleted. _retryloginitpos = 0; } else if (fsLength < _retryloginitpos) { // File changed some unknown way. _retryloginitpos = fsLength; } else { fs.SetLength(_retryloginitpos); } } _retrylogcharpos = 0; // Rewrite all. } sbbuf.Length = 0; string sendstring; lock (retrylogbuf) { int sendchars = retrylogbuf.Length - _retrylogcharpos; if (sendchars > _maxretrylogsendchars) { sendchars = _maxretrylogsendchars; } for (int i = 0; i < sendchars; i++) { sbbuf.Append(retrylogbuf[_retrylogcharpos + i]); } sendstring = sbbuf.ToString(); } #if DEBUG if (!_debugretrylogthrown) { if (-1 != sendstring.IndexOf("kill", StringComparison.OrdinalIgnoreCase)) { _debugretrylogthrown = true; System.Threading.Thread.Sleep(1000 * 8); throw new System.IO.IOException("Debug exception for retrylog"); } } #endif _NormalLog(sendstring); _retrylogcharpos += sendstring.Length; continue; } catch { _retrylogcharpos = -1; // Need to rewrite all. } } else { if (mystop) { bool confirmed = false; try { byte[] expectedMD5hash; long len1; lock (retrylogbuf) { { System.IO.MemoryStream estm = new System.IO.MemoryStream(); System.IO.StreamWriter esw = new System.IO.StreamWriter(estm); esw.Write(retrylogbuf); esw.Flush(); estm.Position = 0; len1 = estm.Length - 0; System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); expectedMD5hash = md5.ComputeHash(estm); } } byte[] gotMD5hash; long len2; { using (System.IO.FileStream fs = new System.IO.FileStream(logFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { fs.Position = _retryloginitpos; len2 = fs.Length - _retrylogcharpos; System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); gotMD5hash = md5.ComputeHash(fs); } } if (expectedMD5hash.Length == gotMD5hash.Length) { for (int i = 0; ; i++) { if (i == expectedMD5hash.Length) { confirmed = true; break; } if (gotMD5hash[i] != expectedMD5hash[i]) { break; } } } } catch { } if (confirmed) { break; } else { _retrylogcharpos = -1; // Need to rewrite all. } } } System.Threading.Thread.Sleep(1000 * 1); } }
private bool WriteFile(FileDataStorage storage, INode iNode) { using (System.IO.FileStream fs = System.IO.File.OpenRead(Path), temp = new System.IO.FileStream(fs.Name + ".temp", System.IO.FileMode.Create)) { if (iNode.Size / 1024 > 8240) { throw new Exception("File size is too big"); } temp.SetLength(63774720); int nodeNum = DataExtractor.GetINodeNum(storage.INodeMap); FSPartsWriter.WriteSuperblock(temp, storage.Superblock); ByteWriter.CopyData(fs, temp, temp.Position, GetBlockEnd(storage.Superblock.ClusterSize, temp.Position), storage.Superblock.ClusterSize); var blocks = BlocksHandler.GetBlocksArr(storage.Bitmap, iNode.Size, storage.Superblock.ClusterSize); for (int i = 0; i < blocks.Length; ++i) { storage.Bitmap.BitmapValue = BitWorker.TurnBitOn(storage.Bitmap.BitmapValue, blocks[i]); } FSPartsWriter.WriteBitmap(temp, storage.Bitmap); ByteWriter.CopyData(fs, temp, temp.Position, GetBlockEnd((Superblock.UsedBlock + Bitmap.UsedBlock) * storage.Superblock.ClusterSize, temp.Position), storage.Superblock.ClusterSize); storage.INodeMap.BitmapValue = BitWorker.TurnBitOn(storage.INodeMap.BitmapValue, nodeNum); FSPartsWriter.WriteBitmap(temp, storage.INodeMap); ByteWriter.CopyData(fs, temp, temp.Position, GetBlockEnd((Superblock.UsedBlock + Bitmap.UsedBlock + Bitmap.UsedBlock) * storage.Superblock.ClusterSize, temp.Position), storage.Superblock.ClusterSize); var dataDict = BlocksHandler.GetDataArr(blocks, storage.Superblock.ClusterSize); List <int> dataKeys = new List <int>(dataDict.Keys); for (int index = 0; index < iNode.Di_addr.Length && index < dataDict.Count; ++index) { iNode.Di_addr[index] = (short)dataKeys[index]; //To change short for int cause data can be lost } long bytesNum = (nodeNum - 1) * INode.Offset; //How many bytes method need to skip ByteWriter.CopyBytes(fs, temp, temp.Position, bytesNum, storage.Superblock.ClusterSize); FSPartsWriter.WriteINode(temp, iNode); ByteWriter.CopyData(fs, temp, temp.Position, (Superblock.UsedBlock + Bitmap.UsedBlock + Bitmap.UsedBlock + storage.NodeBlocksOffset) * storage.Superblock.ClusterSize - 1, storage.Superblock.ClusterSize); for (int i = 0; i < storage.Bitmap.BitmapValue.Length * 8; ++i) { if (dataKeys.Contains(i)) { ByteWriter.WriteBlock(temp, storage.Superblock.ClusterSize, dataDict[i]); } else { ByteWriter.CopyBytes(fs, temp, temp.Position, storage.Superblock.ClusterSize, storage.Superblock.ClusterSize); } } return(true); } }
public override void SetLength(long value) { innerStream.SetLength(value); }
static public void ConvertFolderToPak(string path, ConvertFeedback feedback) { if (feedback != null) { feedback(0); } IPackage package = new PackageFolder("test", path, ""); string outputPath = path + ".pak"; System.IO.FileStream stream = new System.IO.FileStream(outputPath, System.IO.FileMode.Create); stream.SetLength(0); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); // calculate positions int position = 0; List <PakFileInfo> infos = new List <PakFileInfo>(); foreach (string fileName in package.Files) { // exclude pdb files and files starting with . if (fileName.StartsWith(".") || fileName.EndsWith(".pdb", StringComparison.InvariantCultureIgnoreCase)) { continue; } File file = package.GetFile(fileName, FileOpenMode.Read); PakFileInfo info = new PakFileInfo(); info.Name = fileName; info.Position = position; info.Length = (int)file.Stream.Length; position += info.Length; file.Close(); infos.Add(info); } PakHeader header = new PakHeader(); header.FileCount = infos.Count; header.Version = 00010; //0.00.10 header.Type = PackageType.Main; // write header writer.Write(header.FileCount); writer.Write(header.Version); writer.Write((int)header.Type); foreach (PakFileInfo info in infos) { writer.Write(info.Position); writer.Write(info.Length); writer.Write(info.Name); } int written = 0; // write files foreach (PakFileInfo info in infos) { File file = package.GetFile(info.Name, FileOpenMode.Read); int remaining = (int)file.Stream.Length; byte[] buf = new byte[1024 * 1024 * 4]; while (remaining > 0) { int copy = System.Math.Min(buf.Length, remaining); file.Stream.Read(buf, 0, copy); stream.Write(buf, 0, copy); remaining -= copy; } written += (int)file.Stream.Length; file.Close(); if (feedback != null) { feedback(written / (float)position); } } // finish writer.Flush(); writer.Close(); stream.Close(); }