SetLength() public method

Sets the length of this stream to the given value.
public SetLength ( long value ) : void
value long The new length of the stream.
return void
Example #1
0
        private void GenerateBackups()
        {
            var rand = new Random();
            foreach (var path in paths)
            {
                int gb = rand.Next(1, 3);
                var writepath = string.Format("{0}\\{1}.tib", path, DateTime.Now.ToString("MMM-dd-yyyy-fffffff"));

                //50% failure rate per folder!
                if (rand.NextDouble() >= 0.5)
                {
                    //write a file to disk with a filesize between 1-3gb
                    using (var fs = new FileStream(writepath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        try
                        {
                            fs.SetLength(1024 * 1024 * 1024 * gb);
                        }
                        catch (Exception)
                        {
                            fs.SetLength(1024 * 1024 * 1024);
                        }

                    }
                    Console.WriteLine("\tWriting {0} ({1}Gb)", writepath, gb);
                }
                else Console.WriteLine("\tSimulating failure for {0}", path);

            }
        }
Example #2
0
        // Writes zeros to a file stream, with space advantage on compressed and sparse files.
        public static void WriteZeros(System.IO.FileStream fs, long begin, long end)
        {
#if NETSTANDARD2_0
            if (fs.Length < end)
            {
                fs.SetLength(end); // Just extend the length of the file
            }
#else
// Hopefully this works as expected, it's hard to get this working right over the .NET framework

            fs.Flush(); // So that ALL of the buffers are cleared and written to the file.
            zeroinfo zi = new zeroinfo();
            int      retd;
            // Get the file handle
            IntPtr hndl = fs.SafeFileHandle.DangerousGetHandle();
            if (end > fs.Length)
            {
                while (end > fs.Length)
                {
                    long pos   = fs.Length;
                    long write = Math.Min(0x100000, end - pos);
                    fs.SetLength(pos + write);
                    zi.begin = pos;
                    zi.end   = pos + write;
                    SetZeroData(hndl, FSCTL_SET_ZERO_DATA, ref zi, 16, IntPtr.Zero, 0, out retd, IntPtr.Zero);
                }
            }
            zi.begin = begin;
            zi.end   = end;
            SetZeroData(hndl, FSCTL_SET_ZERO_DATA, ref zi, 16, IntPtr.Zero, 0, out retd, IntPtr.Zero);
            fs.Position = end;
#endif
        }
        public void FlushSetLengthAtEndOfBuffer()
        {
            // This is a regression test for a bug with FileStream’s Flush() 
            // and SetLength() methods.
            // The read-buffer was not flushed inside Flush and SetLength when
            // the buffer pointer was at the end. This causes subsequent Seek 
            // and Read calls to operate on stale/wrong data.


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

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

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

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

                // read one byte at Pos = 97
                fs.Seek(97, SeekOrigin.Begin);
                Assert.Equal(fs.ReadByte(), (int)Byte.MaxValue);
            }
        }
Example #4
0
 public void InvalidLengths()
 {
     using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create))
     {
         Assert.Throws<ArgumentOutOfRangeException>("value", () => fs.SetLength(-1));
         Assert.Throws<ArgumentOutOfRangeException>("value", () => fs.SetLength(long.MinValue));
     }
 }
Example #5
0
 public void SetLengthDisposedThrows()
 {
     string fileName = GetTestFilePath();
     using (FileStream fs = new FileStream(fileName, FileMode.Create))
     {
         fs.Dispose();
         Assert.Throws<ObjectDisposedException>(() => fs.SetLength(0));
         // parameter checking happens first
         Assert.Throws<ArgumentOutOfRangeException>("value", () => fs.SetLength(-1));
     }
 }
Example #6
0
        public Stream IncreaseSize(int value, out long offset)
        {
            lock (_lock)
            {
                while (Interlocked.Read(ref _counter) != 0)
                {
                    if (!Monitor.Wait(_lock, 10000, true))
                        throw new NotSupportedException();
                }

                FileStream file = new FileStream(_filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                try
                {
                    offset = MathEx.RoundUp(file.Length, 0x800);
                    file.SetLength(offset + value);
                    _mmf = MemoryMappedFile.CreateFromFile(file, null, 0, MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.Inheritable, false);
                }
                catch
                {
                    file.SafeDispose();
                    throw;
                }

                Interlocked.Increment(ref _counter);
                DisposableStream result = new DisposableStream(_mmf.CreateViewStream(offset, value, MemoryMappedFileAccess.ReadWrite));
                result.AfterDispose.Add(new DisposableAction(Free));
                return result;
            }
        }
        public WriteThroughFileCheckpoint(string filename, string name, bool cached, long initValue = 0)
        {
            _filename = filename;
            _name = name;
            _cached = cached;
            buffer = new byte[4096];
            _memStream = new MemoryStream(buffer);

            var handle = Filenative.CreateFile(_filename,
                            (uint)FileAccess.ReadWrite,
                            (uint)FileShare.ReadWrite,
                            IntPtr.Zero,
                            (uint)FileMode.OpenOrCreate,
                             Filenative.FILE_FLAG_NO_BUFFERING |  (int) FileOptions.WriteThrough,
                            IntPtr.Zero);

            _stream = new FileStream(handle, FileAccess.ReadWrite, 4096);
            var exists = _stream.Length == 4096;
            _stream.SetLength(4096);
            _reader = new BinaryReader(_stream);
            _writer = new BinaryWriter(_memStream);
            if (!exists)
            {
                Write(initValue);
                Flush();
            }
            _last = _lastFlushed = ReadCurrent();
        }
        public FileStreamUnbufferedSequentialWrite(string path, long length, long startPosition, bool truncateOnClose)
        {
            m_path = path;
            m_id = IdentityManager.AcquireIdentity(string.Format("{0}:{1}", this.GetType().Name, m_path));
            m_buffer = BufferManager.AcquireBuffer(m_id, true);
            m_sectorSize = PathUtil.GetDriveSectorSize(m_path);

            m_length = length;
            m_lengthAligned = (m_length + (m_sectorSize - 1)) & (~(long)(m_sectorSize - 1));
            m_truncateOnClose = truncateOnClose;

            const FileMode mode = FileMode.OpenOrCreate;
            const FileAccess access = FileAccess.Write;
            const FileShare share = FileShare.None;
            const FileOptions options = (FileFlagNoBuffering | FileOptions.WriteThrough | FileOptions.SequentialScan);

            m_stream = new FileStream(m_path, mode, access, share, BUFFER_SIZE, options);
            m_stream.SetLength(m_lengthAligned);

            long startPositionAligned = ((startPosition + (m_sectorSize - 1)) & (~(long)(m_sectorSize - 1))) - m_sectorSize;
            if (startPositionAligned >= 0)
                m_stream.Seek(startPositionAligned, SeekOrigin.Begin);
            else
                startPositionAligned = 0;
            m_bufferIndex = (int)(startPosition - startPositionAligned);
        }
        public Logger(String outputLocation)
        {
            if (writer != null)
            {
                writer.Flush();
                writer.Close();
            }

            FileStream ostrm;
            TextWriter oldOut = Console.Out;
            if (outputLocation != null)
            {
                try
                {
                    ostrm = new FileStream(outputLocation.Trim(), FileMode.OpenOrCreate, FileAccess.Write);
                    ostrm.SetLength(0); // clear the file
                    ostrm.Flush();
                    writer = new StreamWriter(ostrm);
                    writer.AutoFlush = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Cannot open " + outputLocation.Trim() + " for writing");
                    Console.WriteLine(e.Message);
                    return;
                }
            }
        }
Example #10
0
 public void Commit( CommitStage c )
 {
   if ( c == CommitStage.Rollback )
   {
     Buffers.Clear();
     UnsavedPageNums.Clear();
     UnsavedAdded = false;
     ReadAvail = 0;
     WriteAvail = 0;   
     CurBufferNum = -1;
   }
   else if ( c == CommitStage.Write )
   {
     foreach ( long bufferNum in UnsavedPageNums )
     {
       byte [] b = GetBuffer( bufferNum );
       long pos = bufferNum << BufferShift;
       long n = Len - pos;
       if ( n > BufferSize ) n = BufferSize;
       if ( BaseStream.Position != pos ) BaseStream.Position = pos;
       BaseStream.Write( b, 0, (int)n );
     }
     UnsavedPageNums.Clear();
     UnsavedAdded = false;
     BaseStream.SetLength( Len );
   }
   else if ( c == CommitStage.Flush )
   {
     BaseStream.Flush( true );
   }
 }
Example #11
0
        public void TestClear1()
        {
            const string fname = "TestClear1.log";
            using (FileStream stream = File.OpenWrite(fname))
            using (var writer = new StreamWriter(stream))
            {
                stream.SetLength(0);
                writer.WriteLine("Test");
            }

            using (var logFile = new LogFile(_scheduler, fname))
            {
                logFile.Property(x => x.Count).ShouldEventually().Be(1, TimeSpan.FromSeconds(5));

                logFile.Count.Should().Be(1);

                using (var stream = new FileStream(fname, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                using (var writer = new StreamWriter(stream))
                {
                    stream.SetLength(0);

                    logFile.Property(x => x.Count).ShouldEventually().Be(0, TimeSpan.FromSeconds(5));
                    logFile.Count.Should().Be(0);

                    writer.WriteLine("Hello World!");
                    writer.Flush();

                    logFile.Property(x => x.Count).ShouldEventually().Be(1, TimeSpan.FromSeconds(5));
                    logFile.Entries.Should().Equal(new[]
                        {
                            new LogLine(0, "Hello World!", LevelFlags.None)
                        });
                }
            }
        }
Example #12
0
		private static void Main(string[] args) {
			Console.WriteLine("bsn GoldParser CGT packer");
			Console.WriteLine("-------------------------");
			Console.WriteLine("(C) 2010 Arsène von Wyss");
			Console.WriteLine();
			if (args.Length == 0) {
				Console.WriteLine("Usage: PackCgt cgtfile [/gzip]");
				Environment.Exit(1);
			}
			try {
				using (FileStream file = new FileStream(args[0], FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) {
					using (MemoryStream packed = new MemoryStream()) {
						CompiledGrammar.Pack(file, packed, (args.Length > 1) && string.Equals(args[1], "/gzip", StringComparison.OrdinalIgnoreCase));
						if (file.Length <= packed.Length) {
							Console.WriteLine("The file size could not be reduced more");
						} else {
							file.Seek(0, SeekOrigin.Begin);
							file.Write(packed.GetBuffer(), 0, (int)packed.Length);
							Console.WriteLine("Reduced file from {0} bytes to {1} bytes", file.Length, packed.Length);
							file.SetLength(packed.Length);
						}
					}
				}
			} catch (Exception ex) {
				Debug.WriteLine(ex, "Error while packing CGT");
				Console.WriteLine("Error: "+ex.Message);
				Environment.Exit(1);
			}
		}
Example #13
0
        /// <summary>
        /// Open datafile - returns true if new
        /// </summary>
        public bool Initialize()
        {
            _log.Write(Logger.DISK, "open datafile '{0}', page size {1}", Path.GetFileName(_filename), BasePage.PAGE_SIZE);

            // open data file (r/w or r)
            _stream = new FileStream(_filename,
                _readonly ? FileMode.Open : FileMode.OpenOrCreate,
                _readonly ? FileAccess.Read : FileAccess.ReadWrite,
                _readonly ? FileShare.Read : FileShare.ReadWrite,
                BasePage.PAGE_SIZE);

            if (_stream.Length == 0)
            {
                _log.Write(Logger.DISK, "initialize new datafile");

                // if has a initial size, reserve this space
                if (_initialSize > 0)
                {
                    _log.Write(Logger.DISK, "initial datafile size {0}", _initialSize);

                    _stream.SetLength(_initialSize);
                }

                return true;
            }
            else
            {
                this.TryRecovery();
                return false;
            }
        }
        public unsafe override void Export(string outPath)
        {
            if (outPath.EndsWith(".wav"))
                WAV.ToFile(CreateStreams()[0], outPath);
            else
            {
                if (_audioSource != DataSource.Empty)
                {
                    int size = WorkingUncompressed.Length + _audioSource.Length;
                    using (FileStream stream = new FileStream(outPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                    {
                        stream.SetLength(size);
                        using (FileMap map = FileMap.FromStreamInternal(stream, FileMapProtect.ReadWrite, 0, size))
                        {
                            VoidPtr addr = map.Address;

                            //Write header
                            Memory.Move(addr, WorkingUncompressed.Address, (uint)WorkingUncompressed.Length);

                            //Set the offset to the audio samples (_dataLocation)
                            *(bint*)(addr + 0x14) = WorkingUncompressed.Length;

                            addr += WorkingUncompressed.Length;

                            //Append audio samples to the end
                            Memory.Move(addr, _audioSource.Address, (uint)_audioSource.Length);
                        }
                    }
                }
                else
                    base.Export(outPath);
            }
        }
Example #15
0
        public static void dealData()
        {
            string path = @"D:\programming_langage_csharp\workspace\DaShiCSharp\data.txt";
            string pathA = @"D:\programming_langage_csharp\workspace\DaShiCSharp\data_new.txt";
            FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
            StreamReader read = new StreamReader(stream);
            string data = read.ReadToEnd();
            read.Close();
            stream.Close();
            FileStream fs = new FileStream(pathA, FileMode.OpenOrCreate, FileAccess.Write);
            fs.SetLength(0);
            StreamWriter write = new StreamWriter(fs);
            Regex regex = new Regex(@"""(?<word>.*?)"",\d*");
            MatchCollection m =  regex.Matches(data);
            ArrayList list = new ArrayList();
            if (m.Count > 0)
            {
                foreach (Match match in m)
                {
                    list.Add(match.Result("${word}"));
                }
            }
            list.Sort(new SortLen());

            foreach(string s in list)
            {
                write.WriteLine(s);
            }
            write.Close();
            fs.Close();
        }
Example #16
0
 public static void Save2Local(string subPath, byte[] bytes)
 {
     try
     {
         string path = GetSandBoxPath(subPath);
         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();
         Debug.LogFormat("Save2Local:{0}", path);
     }
     catch (Exception e)
     {
         Debug.LogErrorFormat("Save2Local:{0} error {1}!", subPath, e.ToString());
     }
 }
        public LocalFileInfo AllocateFile(string fileName, long fileSize)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            if(fileSize < 0)
            {
                throw new ArgumentOutOfRangeException("fileSize");
            }

            string fileDirectory = Path.GetDirectoryName(fileName);
            if (!Directory.Exists(fileDirectory))
            {
                Directory.CreateDirectory(fileDirectory);
            }
            fileName = m_FileNameCorrector.GetFileName(fileName);

            using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                fs.SetLength(fileSize);
            }
            return new LocalFileInfo
                {
                    FileName = fileName
                };
        }
Example #18
0
        public void DesDecrypt(string m_InFilePath, string m_OutFilePath, string sDecrKey)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
            FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);

            byte[] bin = new byte[100];
            long rdlen = 0;
            long totlen = fin.Length;
            int len;

            DES des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
            }

            encStream.Close();
            fout.Close();
            fin.Close();
        }
        /// <summary>
        /// method for locate file on disk
        /// </summary>
        /// <param name="localFile">local file info</param>
        /// <param name="fileName">name of file</param>
        /// <param name="fileSize">size of file</param>
        /// <returns>local file</returns>
        public static string LocateLocalFile(string localFile, string fileName, long fileSize)
        {
            string newFileName = localFile;

            if (!Directory.Exists(localFile))
            {
                Directory.CreateDirectory(localFile);
            }

            if (new FileInfo(localFile).Exists)
            {
                int currentVersion = 0;
                do
                {
                    newFileName = localFile + currentVersion.ToString(CultureInfo.CurrentCulture);
                }
                while (new FileInfo(newFileName).Exists);
            }

            using (FileStream fs = new FileStream(localFile + "\\" + fileName, FileMode.Create, FileAccess.Write))
            {
                fs.SetLength(Math.Max(fileSize, 0));
            }

            return newFileName;
        }
Example #20
0
 /// <summary>
 /// 预分配磁盘空间
 /// </summary>
 /// <param name="saveFileName"></param>
 /// <param name="fileLen"></param>
 private void PreAlloc(string saveFileName, long fileLen)
 {
     using (FileStream fs =new FileStream(saveFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None))
     {
         fs.SetLength(fileLen);
     }
 }
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     string stringData = "";
      //System.Environment.CurrentDirectory +
     string strDir = "TimeData.txt";
     try
     {
         FileStream TimeData = new FileStream(strDir, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
         StreamWriter sw = new StreamWriter(TimeData);
         TimeData.SetLength(0);
         stringData = ((ComboBoxItem)this.ComboBox1.SelectedItem).Content.ToString();
         sw.WriteLine(stringData);
         stringData = ((ComboBoxItem)this.ComboBox2.SelectedItem).Content.ToString();
         sw.WriteLine(stringData);
         stringData = ((ComboBoxItem)this.ComboBox3.SelectedItem).Content.ToString();
         sw.WriteLine(stringData);
         stringData = ((ComboBoxItem)this.ComboBox4.SelectedItem).Content.ToString();
         sw.WriteLine(stringData);
         sw.Close();
     }
     catch (IOException ex)
     {
         MessageBox.Show("出现了一个IO异常!","异常");
         MessageBox.Show(ex.ToString());
         return;
     }
     ChangArgEvent();
     this.Close();
 }
Example #22
0
 /// <summary>
 /// Creates an empty file
 /// </summary>
 /// <param name="fileInfo">File to create</param>
 /// <param name="length">Length of file</param>
 private void CreateEmptyFile(IO.FileInfo fileInfo, int length)
 {
     fileInfo.Directory.Create();
     IO.FileStream fstream = fileInfo.OpenWrite();
     fstream.SetLength(length);
     fstream.Close();
 }
Example #23
0
        /// <summary>
        /// 写入日志文件,可附加
        /// </summary>
        /// <param name="LogName">文件名</param>
        /// <param name="WriteInfo">日志信息</param>
        public static void WriteLog(string LogName, string WriteInfo)
        {
            try
            {
                if (!Directory.Exists(WTGOperation.logPath)) { Directory.CreateDirectory(WTGOperation.logPath); }
                if (File.Exists(WTGOperation.logPath + "\\" + LogName)) { File.Delete(WTGOperation.logPath + "\\" + LogName); }
                using (FileStream fs0 = new FileStream(WTGOperation.logPath + "\\" + LogName, FileMode.Append, FileAccess.Write))
                {
                    fs0.SetLength(0);
                    using (StreamWriter sw0 = new StreamWriter(fs0, Encoding.Default))
                    {
                        string ws0 = "";

                        ws0 = Application.ProductName + Application.ProductVersion;
                        sw0.WriteLine(ws0);
                        ws0 = DateTime.Now.ToString();
                        sw0.WriteLine(ws0);
                        ws0 = WriteInfo;
                        sw0.WriteLine(ws0);

                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }

            //sw0.Close();
        }
Example #24
0
        private void SendButton_Click(object sender, EventArgs e)
        {
            var reader = new BinaryReader(new FileStream(file_location_txtbx.Text, FileMode.Open));
            byte[] fileData = new byte[reader.BaseStream.Length + 1];
            reader.BaseStream.Read(fileData, 1, (int)reader.BaseStream.Length);
            reader.Close();
            fileData[0] = (byte)'c';

            m_client = new ClientContext(@"http://" + ip_address_txtbx.Text + ":" + port_txtbx.Text + "/");

            m_client.SendData(fileData);

            //Bad. Do not use while loop to wait for response, handle this with a trigger somehow. Maybe a timer to ping in every so often.
            //Don't sit and spin in a GUI thread
            while (m_client.data_available == false)
                Thread.Sleep(50);

            var new_data = m_client.ReceiveData();
            FileStream new_file = new FileStream(file_location_txtbx.Text + ".comp", FileMode.OpenOrCreate);
            new_file.SetLength(0);
            new_file.Position = 0;
            new_file.Write(new_data, 0, new_data.Length);
            new_file.Close();

            MessageBox.Show( "Compression Complete","", MessageBoxButtons.OK);
        }
        public static void ConvertFromBase64(string inputFilePath, string outputFilePath)
        {
            //Create the file streams to handle the input and output files.
            FileStream fin = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);

            FromBase64Transform transformer = new FromBase64Transform();

            //Create variables to help with read and write below.
            //This is intermediate storage for the decryption:
            byte[] bin = new byte[fin.Length / transformer.InputBlockSize * transformer.OutputBlockSize];
            long rdlen = 0;              //This is the total number of bytes written.
            long totlen = fin.Length;    //This is the total length of the input file.
            int len;                     //This is the number of bytes to be written at a time.

            CryptoStream encStream = new CryptoStream(fout, transformer, CryptoStreamMode.Write);

            //Read from the input file, then decrypt and write to the output file.
            while(rdlen < totlen)
            {
                len = fin.Read(bin, 0, (int)fin.Length);
                encStream.Write(bin, 0, len);
                rdlen = (rdlen + ((len / transformer.InputBlockSize) * transformer.OutputBlockSize));
            }

            encStream.Close();
            fout.Close();
            fin.Close();
        }
        public MemoryMappedFileCheckpoint(string filename, string name, bool cached, bool mustExist = false, long initValue = 0)
        {
            _filename = filename;
            _name = name;
            _cached = cached;
            var old = File.Exists(_filename);
            _fileStream = new FileStream(_filename,
                                         mustExist ? FileMode.Open : FileMode.OpenOrCreate,
                                         FileAccess.ReadWrite,
                                         FileShare.ReadWrite);
            _fileStream.SetLength(sizeof(long));
            _file = MemoryMappedFile.CreateFromFile(_fileStream,
                                                    Guid.NewGuid().ToString(),
                                                    sizeof(long),
                                                    MemoryMappedFileAccess.ReadWrite,
                                                    new MemoryMappedFileSecurity(),
                                                    HandleInheritability.None,
                                                    false);
            _accessor = _file.CreateViewAccessor(0, sizeof(long));

            if (old)
                _last = _lastFlushed = ReadCurrent();
            else
            {
                _last = initValue;
                Flush();
            }
        }
Example #27
0
 private void button2_Click(object sender, EventArgs e)
 {
     string str1 = textBox1.Text;
     string strPwd = textBox2.Text;
     string str2 = textBox3.Text;
     try
     {
         byte[] myIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
         byte[] myKey = System.Text.Encoding.UTF8.GetBytes(strPwd);
         FileStream myFileIn = new FileStream(str1, FileMode.Open, FileAccess.Read);
         FileStream myFileOut = new FileStream(str2, FileMode.OpenOrCreate, FileAccess.Write);
         myFileOut.SetLength(0);
         byte[] myBytes = new byte[100];
         long myLength = myFileIn.Length;
         long myInLength = 0;
         DES myProvider = new DESCryptoServiceProvider();
         CryptoStream myDeStream = new CryptoStream(myFileOut, myProvider.CreateDecryptor(myKey, myIV), CryptoStreamMode.Write);
         while (myInLength < myLength)
         {
             int mylen = myFileIn.Read(myBytes, 0, 100);
             myDeStream.Write(myBytes, 0, mylen);
             myInLength += mylen;
         }
         myDeStream.Close();
         myFileOut.Close();
         myFileIn.Close();
         MessageBox.Show("解密文件成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
Example #28
0
        private void GetMp3File()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fileUrl);
            request.Method = "GET";
            WebResponse res = request.GetResponse();
            if(res.ContentType.Contains("x-aac"))
                _filePath = DateTime.Now.ToString("yyyy-MM-ddThh-mm-ss") + ".aac";
            else
                _filePath = DateTime.Now.ToString("yyyy-MM-ddThh-mm-ss") + ".mp3";

            Byte[] buffer = new Byte[_bufferLength];
            FileStream writer = new FileStream(_filePath, FileMode.Create, FileAccess.ReadWrite,FileShare.Read);
            writer.SetLength(res.ContentLength);
            Stream stream = res.GetResponseStream();
            int nRead = 0;
            while (_readBytesCount < res.ContentLength )
            {
                nRead = stream.Read(buffer, 0, _bufferLength);
                _readBytesCount += nRead;
                Debug.WriteLine("Read :: " + _readBytesCount);
                writer.Write(buffer,0,nRead);
                writer.Flush();

            }
            writer.Close();
        }
Example #29
0
        /// <summary>
        /// MBR+UEFI脚本Write到WTGOperation.diskpartscriptpath + @"\uefimbr.txt
        /// </summary>
        /// <param name="efisize">efisize(MB)</param>
        /// <param name="ud">优盘盘符,":"、"\"不必须</param>
        public static string GenerateMBRAndUEFIScript(string efisize, string ud)
        {
            using (FileStream fs0 = new FileStream(WTGModel.diskpartScriptPath + @"\uefimbr.txt", FileMode.Create, FileAccess.Write))
            {
                fs0.SetLength(0);
                using (StreamWriter sw0 = new StreamWriter(fs0, Encoding.Default))
                {
                    //string ws0 = "";

                    sw0.WriteLine("select volume " + ud.Substring(0, 1));
                    sw0.WriteLine("clean");
                    sw0.WriteLine("convert mbr");
                    sw0.WriteLine("create partition primary size " + efisize);
                    sw0.WriteLine("create partition primary");
                    sw0.WriteLine("select partition 1");
                    sw0.WriteLine("format fs=fat quick");
                    sw0.WriteLine("assign letter=x");
                    sw0.WriteLine("select partition 2");
                    sw0.WriteLine("format fs=ntfs quick");
                    sw0.WriteLine("assign letter=" + ud.Substring(0, 1));
                    sw0.WriteLine("exit");
                }

            }
            return WTGModel.diskpartScriptPath + @"\uefimbr.txt";
        }
Example #30
0
        private void CreatePieFile(string PieFileFullName, long DriveFreeSpace, string DriveFreeSpaceAsString)
        {
            if (DriveFreeSpace <= 0)
            {
                Message.Instance.PrintError("There is no free space available. Operation is aborted.");
                return;
            }

            Message.Instance.PrintMessage(
                string.Format("Creating file {0} with size of {1}...",
                PieFileFullName, DriveFreeSpaceAsString)
                );

            try
            {
                using (var fs = new FileStream(PieFileFullName, FileMode.CreateNew, FileAccess.Write))
                {
                    fs.SetLength(DriveFreeSpace);
                    fs.Close();
                    Message.Instance.PrintMessage("Done.");
                }
            }
            catch(Exception ex)
            {
                Message.Instance.PrintError(ex.Message);
            }
        }
Example #31
0
        private void writeprogress_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (IsUserClosing)
            {
                DialogResult dResult = MessageBox.Show(MsgManager.GetResString("Msg_WritingAbort"), MsgManager.GetResString("Msg_Tip"), MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
                if (dResult == DialogResult.Yes)
                {
                    IsUserClosing = false;
                    OnClosingException = new UserCancelException();
                }
                else
                {
                    e.Cancel = true;
                }
            }
            try
            {
                //if (System.IO.Directory .Exists ())
                FileStream fs = new FileStream(WTGModel.logPath + "\\" + DateTime.Now.ToFileTime() + ".log", FileMode.Create, FileAccess.Write);
                fs.SetLength(0);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                string ws = "";
                ws = Application.StartupPath + "\r\n程序版本:" + Application.ProductVersion + "\r\n" + System.DateTime.Now;
                sw.WriteLine(ws);
                ws = textBox1.Text;
                sw.WriteLine(ws);
                sw.Close();
                textBox1.Text = "";
            }
            catch (Exception ex)
            {
                Log.WriteLog("WriteProgressFormClosingError.log", ex.ToString());
            }

        }
 public static FileEventPointer OpenOrCreateForWriting(string fullName)
 {
     var stream = new FileStream(fullName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     if (stream.Length == 0)
         stream.SetLength(8);
     return new FileEventPointer(stream, true);
 }
Example #33
0
		public static void Execute(StorageEnvironmentOptions srcOptions, StorageEnvironmentOptions.DirectoryStorageEnvironmentOptions compactOptions, Action<CompactionProgress> progressReport = null)
		{
			if (srcOptions.IncrementalBackupEnabled)
				throw new InvalidOperationException(CannotCompactBecauseOfIncrementalBackup);

			long minimalCompactedDataFileSize;

			srcOptions.ManualFlushing = true; // prevent from flushing during compaction - we shouldn't touch any source files
			compactOptions.ManualFlushing = true; // let us flush manually during data copy

			using(var existingEnv = new StorageEnvironment(srcOptions))
			using (var compactedEnv = new StorageEnvironment(compactOptions))
			{
				CopyTrees(existingEnv, compactedEnv, progressReport);

				compactedEnv.FlushLogToDataFile(allowToFlushOverwrittenPages: true);

				compactedEnv.Journal.Applicator.SyncDataFile(compactedEnv.OldestTransaction);
				compactedEnv.Journal.Applicator.DeleteCurrentAlreadyFlushedJournal();

				minimalCompactedDataFileSize = compactedEnv.NextPageNumber*AbstractPager.PageSize;
			}

			using (var compactedDataFile = new FileStream(Path.Combine(compactOptions.BasePath, Constants.DatabaseFilename), FileMode.Open, FileAccess.ReadWrite))
			{
				compactedDataFile.SetLength(minimalCompactedDataFileSize);
			}
		}
Example #34
0
		/// <summary>
		/// 加密文件
		/// </summary>
		/// <param name="inName">来源文件</param>
		/// <param name="outName">输出文件</param>
		/// <param name="Algorithm">对称算法</param>
		public static void EncryptFile(string inName, string outName, SymmetricAlgorithm Algorithm)
		{
			FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
			using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
			{
				fout.SetLength(0);

				CryptoStream encStream = new CryptoStream(fout, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);

				//Read from the input file, then encrypt and write to the output file.
				//Create variables to help with read and write.
				long rdlen = 0;					//This is the total number of bytes written.
				int len;						//This is the number of bytes to be written at a time.
				byte[] bin = new byte[FileReadStep];
				while (rdlen < fin.Length)
				{
					len = fin.Read(bin, 0, FileReadStep);
					encStream.Write(bin, 0, len);
					rdlen += len;
				}

				encStream.Close();
				fin.Close();
			}
		}
Example #35
0
 public static void WriteContent(byte[] data, string filename)
 {
     using (System.IO.FileStream hStream = System.IO.File.Open(filename, FileMode.Open)) {
         hStream.SetLength((int)data.Length);
         hStream.Write(data, 0, (int)data.Length);
         hStream.Close();
     }
 }
Example #36
0
        public override void SetLength(long value)
        {
            if (_m_disposed)
            {
                throw ADP.ObjectDisposed(this);
            }

            _m_fs.SetLength(value);
        }
Example #37
0
 public void DownloadToFile(string File)
 {
     byte[] bin = DownloadCore();
     System.IO.FileStream fStm = new System.IO.FileStream(File, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
     fStm.SetLength(0);
     fStm.Write(bin, 0, bin.Length);
     bin = null;
     fStm.Close();
     fStm.Dispose();
 }
Example #38
0
        private void WipeFile(FileModel file)
        {
            try
            {
                int timesToWrite = 10;
                sysIo.File.SetAttributes(file.Path, sysIo.FileAttributes.Normal);
                double sectors               = Math.Ceiling(new sysIo.FileInfo(file.Path).Length / 512.0);
                byte[] dummyBuffer           = new byte[512];
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                for (int i = 0; i <= 3; i++)
                {
                    byte[] inFile = sysIo.File.ReadAllBytes(file.Path);
                    AES.SetDefaultKey(FileControls.GenerateRandomKey(25));
                    if (inFile.Length > 0)
                    {
                        sysIo.FileStream inputStream = new sysIo.FileStream(file.Path, sysIo.FileMode.Open);
                        byte[]           data        = AES.Encrypt(inFile);
                        inputStream.SetLength(0);
                        inputStream.Seek(0, sysIo.SeekOrigin.Begin);
                        inputStream.Write(data, 0, data.Length);

                        for (int passIndex = 0; passIndex < timesToWrite; passIndex++)
                        {
                            inputStream.Position = 0;
                            for (int sectorIndex = 0; sectorIndex < sectors; sectorIndex++)
                            {
                                rng.GetBytes(dummyBuffer);
                                inputStream.Write(dummyBuffer, 0, dummyBuffer.Length);
                            }
                        }
                        inputStream.Close();
                    }
                }

                sysIo.FileStream instream = new sysIo.FileStream(file.Path, sysIo.FileMode.Open);
                instream.SetLength(0);
                instream.Close();

                DateTime dt = new DateTime(2037, 1, 1, 0, 0, 0);
                sysIo.File.SetCreationTime(file.Path, dt);
                sysIo.File.SetLastAccessTime(file.Path, dt);
                sysIo.File.SetLastWriteTime(file.Path, dt);

                sysIo.File.SetCreationTimeUtc(file.Path, dt);
                sysIo.File.SetLastAccessTimeUtc(file.Path, dt);
                sysIo.File.SetLastWriteTimeUtc(file.Path, dt);

                sysIo.File.Delete(file.Path);
                AES.UnsetDefaultKey();
            }
            catch (Exception ex)
            {
                Logging.LogError(LoggingLevel.Error, "File Wipe Failed", ex);
            }
        }
Example #39
0
 static void CreateDiskImage(System.IO.FileStream fs, FATFormatInfo fi)
 {
     if (fs.Length != 0)
     {
         fs.SetLength(0);
     }
     FileCompression.CompressStream(fs);
     FileCompression.SetSparse(fs);
     FileCompression.WriteZeros(fs, 0, fi.TotalSectors * 512);
     FormatDiskImage(fs, fi, false);
 }
Example #40
0
 static public int SetLength(IntPtr l)
 {
     try {
         System.IO.FileStream self = (System.IO.FileStream)checkSelf(l);
         System.Int64         a1;
         checkType(l, 2, out a1);
         self.SetLength(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 public override void Flush()
 {
   foreach ( long bufferNum in UnsavedPageNums )
   {
     byte [] b = GetBuffer( bufferNum );
     long pos = bufferNum << BufferShift;
     long n = Len - pos;
     if ( n > BufferSize ) n = BufferSize;
     if ( BaseStream.Position != pos ) BaseStream.Position = pos;
     BaseStream.Write( b, 0, (int)n );
   }
   UnsavedPageNums.Clear();
   UnsavedAdded = false;
   BaseStream.SetLength( Len );
   BaseStream.Flush( true );
 }
        public void RecvFristDataHandler(TcpSocketSaeaSession session)
        {
            var data = GetMessageEntity <FileFristUploadDataPack>(session);

            if (data.FileMode == 0)
            {
                _fileStream.Position = 0;
                _fileStream.SetLength(0);
            }
            else
            {
                _fileStream.Position = data.Position;
            }

            this.WriteFileAsync(data.Data, data.FileSize);
        }
Example #43
0
    protected virtual void onSavePlayerDatClick(object sender, EventArgs e)
    {
        if (playerDat == null)
        {
            throw new Exception("player.dat is not opened");
        }

        playerDat.SetLength(0);
        BinaryFormatter binaryFormatter = new BinaryFormatter();

        binaryFormatter.Serialize(playerDat, vars);
        binaryFormatter.Serialize(playerDat, stringVars);

        playerDat.Flush();

        //playerDat.Close();
    }
Example #44
0
        public void TurnOn()
        {
            // create persistent file if it doesn't exist yet
            if (!System.IO.File.Exists(filename))
            {
                System.IO.FileStream fs = System.IO.File.Create(filename, BYTES_PER_SECTOR);
                fs.SetLength(BYTES_PER_SECTOR * SECTOR_COUNT);
                fs.Flush();
                fs.Close();
            }

            stream = System.IO.File.Open(filename, FileMode.Open, FileAccess.ReadWrite);
            if (stream == null)
            {
                throw new Exception("Failed to open file");
            }

            powerOn = true;
        }
Example #45
0
    /// <summary>
    /// Записывает в файл сохранения измения из объекта с данными сохранения
    /// </summary>
    /// <param name="saveInformation">Объект с данными сохранения</param>
    /// <returns></returns>
    public bool WriteInSaveFile(SaveGameInformation saveInformation)
    {
        try
        {
            System.Xml.Serialization.XmlSerializer writer =
                new System.Xml.Serialization.XmlSerializer(typeof(SaveGameInformation));
            System.IO.FileStream file = System.IO.File.Open(PATH_SAVE_FILE + ".xml", FileMode.Open);
            file.SetLength(0);
            writer.Serialize(file, saveInformation);
            file.Close();

            return(true);
        }
        catch (Exception ex)
        {
            Debug.LogError("WriteInSaveFile - " + ex.Message);
            return(false);
        }
    }
        // System IO write file(Save Password)
        public void createPass()
        {
            dummy         = CMD_LINE.Text.ToUpper();
            inputDataSize = dummy.Length;
            CMD_LINE.Text = "";
            if (inputDataSize > 0)
            {
                byte[] byteArray0 = System.Text.Encoding.Unicode.GetBytes(dummy);
                inputData = new byte[byteArray0.Length];
                for (int i = 0; i < byteArray0.Length; i++)
                {
                    inputData[i] = byteArray0[i];
                }

                inputDataSize = byteArray0.Length;
                using (System.IO.FileStream hStream = System.IO.File.Open(@SAVE_PASS, FileMode.Create)) {
                    hStream.SetLength((int)inputDataSize);
                    hStream.Write(inputData, 0, (int)inputDataSize);
                    hStream.Close();
                }
                old();
            }
        }
        // System IO write file(Save Password)
        public void saveFile(string data, string location)
        {
            string SAVE_FILE = "/Documents/" + location;

            dummy         = data;
            inputDataSize = dummy.Length;
            if (inputDataSize > 0)
            {
                byte[] byteArray0 = System.Text.Encoding.ASCII.GetBytes(dummy);
                inputData = new byte[byteArray0.Length];
                for (int i = 0; i < byteArray0.Length; i++)
                {
                    inputData[i] = byteArray0[i];
                }

                inputDataSize = byteArray0.Length;
                using (System.IO.FileStream hStream = System.IO.File.Open(@SAVE_FILE, FileMode.CreateNew)) {
                    hStream.SetLength((int)inputDataSize);
                    hStream.Write(inputData, 0, (int)inputDataSize);
                    hStream.Close();
                }
            }
        }
Example #48
0
        public NtStatus SetEof(long length)
        {
            try
            {
                var(stream, streamFromCache) = GetStream(true);

                stream.SetLength(length);
                stream.Flush();

                if (!streamFromCache)
                {
                    stream.Close(); //#TODO cache
                }
                file.Refresh();
                FileInformation.Length = length;
                return(DokanResult.Success);
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine("DokanPBO::SetEof failed due to FileNotFoundException: " + e);
                return(DokanResult.FileNotFound);
            } //#TODO access denied
        }
Example #49
0
		private void EncryptOrDecryptFile(string strInputFile, string strOutputFile, byte[] bytKey, byte[] bytIV, CryptoAction Direction)
		{
			try //In case of errors.
			{

				//Setup file streams to handle input and output.
				fsInput = new System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read);
				fsOutput = new System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write);
				fsOutput.SetLength(0); //make sure fsOutput is empty

				//Declare variables for encrypt/decrypt process.
				byte[] bytBuffer = new byte[4097]; //holds a block of bytes for processing
				long lngBytesProcessed = 0; //running count of bytes processed
				long lngFileLength = fsInput.Length; //the input file's length
				int intBytesInCurrentBlock = 0; //current bytes being processed
				CryptoStream csCryptoStream = null;
				//Declare your CryptoServiceProvider.
				System.Security.Cryptography.RijndaelManaged cspRijndael = new System.Security.Cryptography.RijndaelManaged();
				//Setup Progress Bar
				pbStatus.Value = 0;
				pbStatus.Maximum = 100;

				//Determine if ecryption or decryption and setup CryptoStream.
				switch (Direction)
				{
					case CryptoAction.ActionEncrypt:
						csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateEncryptor(bytKey, bytIV), CryptoStreamMode.Write);

						break;
					case CryptoAction.ActionDecrypt:
						csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateDecryptor(bytKey, bytIV), CryptoStreamMode.Write);
						break;
				}

				//Use While to loop until all of the file is processed.
				while (lngBytesProcessed < lngFileLength)
				{
					//Read file with the input filestream.
					intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096);
					//Write output file with the cryptostream.
					csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock);
					//Update lngBytesProcessed
					lngBytesProcessed = lngBytesProcessed + System.Convert.ToInt64(intBytesInCurrentBlock);
					//Update Progress Bar
					pbStatus.Value = System.Convert.ToInt32((lngBytesProcessed / (double)lngFileLength) * 100);
				}

				//Close FileStreams and CryptoStream.
				csCryptoStream.Close();
				fsInput.Close();
				fsOutput.Close();

				//If encrypting then delete the original unencrypted file.
				if (Direction == CryptoAction.ActionEncrypt)
				{
					FileInfo fileOriginal = new FileInfo(strFileToEncrypt);
					fileOriginal.Delete();
				}

				//If decrypting then delete the encrypted file.
				if (Direction == CryptoAction.ActionDecrypt)
				{
					FileInfo fileEncrypted = new FileInfo(strFileToDecrypt);
					fileEncrypted.Delete();
				}

				//Update the user when the file is done.
				string Wrap = "\r" + "\n";
				if (Direction == CryptoAction.ActionEncrypt)
				{
					MessageBox.Show("Encryption Complete" + Wrap + Wrap + "Total bytes processed = " + lngBytesProcessed.ToString(), "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);

					//Update the progress bar and textboxes.
					pbStatus.Value = 0;
					txtFileToEncrypt.Text = "Click Browse to load file.";
					txtPassEncrypt.Text = "";
					txtConPassEncrypt.Text = "";
					txtDestinationEncrypt.Text = "";
					btnChangeEncrypt.Enabled = false;
					btnEncrypt.Enabled = false;

				}
				else
				{
					//Update the user when the file is done.
					MessageBox.Show("Decryption Complete" + Wrap + Wrap + "Total bytes processed = " + lngBytesProcessed.ToString(), "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);

					//Update the progress bar and textboxes.
					pbStatus.Value = 0;
					txtFileToDecrypt.Text = "Click Browse to load file.";
					txtPassDecrypt.Text = "";
					txtConPassDecrypt.Text = "";
					txtDestinationDecrypt.Text = "";
					btnChangeDecrypt.Enabled = false;
					btnDecrypt.Enabled = false;
				}


				//Catch file not found error.
			}
//TODO: INSTANT C# TODO TASK: There is no C# equivalent to 'When'
//TODO: INSTANT C# TODO TASK: Calls to the VB 'Err' object are not converted by Instant C#:
			catch // When Err.Number = 53 //if file not found
			{
				MessageBox.Show("Please check to make sure the path and filename" + "are correct and if the file exists.", "Invalid Path or Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

				//Catch all other errors. And delete partial files.
			
				fsInput.Close();
				fsOutput.Close();

				if (Direction == CryptoAction.ActionDecrypt)
				{
					FileInfo fileDelete = new FileInfo(txtDestinationDecrypt.Text);
					fileDelete.Delete();
					pbStatus.Value = 0;
					txtPassDecrypt.Text = "";
					txtConPassDecrypt.Text = "";

					MessageBox.Show("Please check to make sure that you entered the correct" + "password.", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				}
				else
				{
					FileInfo fileDelete = new FileInfo(txtDestinationEncrypt.Text);
					fileDelete.Delete();

					pbStatus.Value = 0;
					txtPassEncrypt.Text = "";
					txtConPassEncrypt.Text = "";

					MessageBox.Show("This file cannot be encrypted.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

				}

			}
		}
Example #50
0
 public override void SetLength(long value)
 {
     tempStream.SetLength(value);
 }
Example #51
0
    private void OnDownloadPreviewComplete(object sender, DownloadDataCompletedEventArgs e)
    {
        lock (handler)
        {
            handler.Add(() => {
                if (e.Error != null)
                {
                    if (processingCtrl != null)
                    {
                        if (processingCtrl.retryNum >= 1)
                        {
                            //跳过这个任务,开始下载下一个的预览图
                            lock (PreviewTask)
                            {
                                if (PreviewTask.Contains(processingCtrl))
                                {
                                    PreviewTask.Remove(processingCtrl);
                                }
                            }
                        }
                        else
                        {
                            processingCtrl.retryNum++;
                        }
                    }

                    if (client != null)
                    {
                        client.Dispose();
                        client = null;
                    }
                    processingCtrl = null;
                    processing     = false;
                }
                else
                {
                    if (processingCtrl == null)
                    {
                        //保存到本地,下次直接从本地读取.
                        //中断得下载预览图任务存储路径
                        if (!string.IsNullOrEmpty(cancelPreviewTask))
                        {
                            byte[] bitPrev = e.Result;
                            if (bitPrev != null && bitPrev.Length != 0)
                            {
                                System.IO.FileStream fs = new System.IO.FileStream(cancelPreviewTask, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None);
                                fs.Write(bitPrev, 0, bitPrev.Length);
                                fs.SetLength(bitPrev.Length);
                                fs.Flush();
                                fs.Close();
                                lock (PreviewTaskCache)
                                {
                                    PreviewTaskCache.Add(cancelPreviewTask);
                                }
                            }
                        }
                        processing = false;
                        return;
                    }
                    byte[] bitIcon = e.Result;
                    if (bitIcon != null && bitIcon.Length != 0)
                    {
                        if (processingCtrl.Target != null)
                        {
                            try
                            {
                                lock (PreviewTask)
                                {
                                    if (PreviewTask.Contains(processingCtrl))
                                    {
                                        System.IO.FileStream fs = new System.IO.FileStream(processingCtrl.Target.Preview, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None);
                                        fs.Write(bitIcon, 0, bitIcon.Length);
                                        fs.SetLength(bitIcon.Length);
                                        fs.Flush();
                                        fs.Close();
                                        PreviewTask.Remove(processingCtrl);
                                    }
                                }
                            }
                            catch (System.Exception exp)
                            {
                                Debug.Log(exp.Message);
                            }
                            Texture2D tex = new Texture2D(200, 150);
                            tex.LoadImage(bitIcon);
                            processingCtrl.Preview.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero);
                            lock (PreviewTaskCache)
                            {
                                PreviewTaskCache.Add(processingCtrl.Target.Preview);
                            }
                            client.Dispose();
                            client         = null;
                            processingCtrl = null;
                            processing     = false;
                        }
                        else if (processingCtrl.Chapter != null)
                        {
                            lock (PreviewTask)
                            {
                                if (PreviewTask.Contains(processingCtrl))
                                {
                                    if (bitIcon != null && bitIcon.Length != 0)
                                    {
                                        System.IO.File.WriteAllBytes(processingCtrl.Chapter.Preview, bitIcon);
                                        Texture2D tex = new Texture2D(200, 150);
                                        tex.LoadImage(bitIcon);
                                        processingCtrl.Preview.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero);
                                    }
                                    PreviewTask.Remove(processingCtrl);
                                }
                            }

                            lock (PreviewTaskCache)
                            {
                                PreviewTaskCache.Add(processingCtrl.Chapter.Preview);
                            }
                            client.Dispose();
                            client         = null;
                            processingCtrl = null;
                            processing     = false;
                        }
                    }
                }
            });
        }
    }
Example #52
0
        private void Rebuild()
        {
            sio.FileStream   fsw = null;
            sio.BinaryWriter bww = null;
            sio.FileStream   fsr = null;
            sio.BinaryReader brr = null;
            sio.BinaryWriter brw = null;
            sio.MemoryStream ms  = null;
            sio.BinaryReader br  = null;
            sio.BinaryWriter bw  = null;
            sio.FileInfo     fi;
            int  dataLen;
            bool dataStartPositioned = true;

            byte[] tb, b;
            string tocPath;
            int    mod, modAct;
            int    bytesWritten;
            int    maxBR, curBR, temBR;
            bool   error     = false;
            string errorText = "";
            int    idx;
            int    i, j;

            int   m;
            ModCB Mod = delegate(int val)
            {
                m = val % filesMod;
                if (m == 0)
                {
                    return(val);
                }
                else
                {
                    return(val + (filesMod - m));
                }
            };

            try
            {
                fsw = new sio.FileStream(imgPath, sio.FileMode.Create, sio.FileAccess.Write, sio.FileShare.None);
                bww = new sio.BinaryWriter(fsw, ste.Default);

                fsr = new sio.FileStream(toc.fils[2].path, sio.FileMode.Open, sio.FileAccess.ReadWrite, sio.FileShare.None);
                brr = new sio.BinaryReader(fsr, ste.Default);
                ms  = new sio.MemoryStream(brr.ReadBytes((int)fsr.Length), true);
                br  = new sio.BinaryReader(ms, ste.Default);
                bw  = new sio.BinaryWriter(ms, ste.Default);

                ms.Position     = 0x400;
                toc.fils[2].pos = 0;
                toc.fils[3].pos = 0x2440;
                bw.WriteInt32BE(toc.fils[3].len); //ldr len
                ms.Position += 0x1c;
                i            = Mod(0x2440 + toc.fils[3].len);
                bw.WriteInt32BE(i); //dol start
                toc.fils[4].pos = i;
                i = Mod(i + toc.fils[4].len);
                bw.WriteInt32BE(i); //toc start
                tocPath          = toc.fils[5].path;
                toc.fils[5].path = sio.Path.GetTempPath() + "game.toc";
                toc.fils[5].pos  = i;
                toc.dataStart    = 0;
                tb = ReGenTOC(toc.fils[5].pos, out toc.fils[5].len, ref toc.dataStart, out toc.totalLen);
                if (appendImage)
                {
                    dataLen       = toc.totalLen - toc.dataStart;
                    toc.dataStart = maxImageSize - dataLen;
                    tb            = ReGenTOC(toc.fils[5].pos, out toc.fils[5].len, ref toc.dataStart, out toc.totalLen);
                }
                bw.WriteInt32BE(toc.fils[5].len); //toc len
                bw.WriteInt32BE(toc.fils[5].len); //total toc len
                ms.Position += 0x04;
                bw.WriteInt32BE(toc.dataStart);   //data start
                ms.WriteTo(fsw);
                if (miOptionsModifySystemFiles.Checked)
                {
                    fsr.Position = 0;
                    ms.WriteTo(fsr);
                    brr.Close();
                    fsr.Close();
                    fsr = new sio.FileStream(tocPath, sio.FileMode.Create, sio.FileAccess.Write, sio.FileShare.None);
                    brw = new sio.BinaryWriter(fsr, ste.Default);
                    brw.Write(tb);
                    brw.Close();
                    fsr.Close();
                }
                else
                {
                    brr.Close();
                    fsr.Close();
                }
                br.Close();
                bw.Close();
                ms.Close();
                brr.Close();
                fsr.Close();

                bytesWritten = (int)fsw.Position;
                //if (resPath.Substring(0, 2).ToLower() == imgPath.Substring(0, 2).ToLower())
                //    maxBR = 0x0800000;
                //else
                maxBR = 0x8000;
                curBR = maxBR - bytesWritten;

                ResetProgressBar(0, 100, 0);
                mod = (int)Math.Floor((float)toc.totalLen / sspbProgress.Maximum);
                mod = (mod | (maxBR - 1)) + 1;
                i   = (int)Math.Ceiling((float)toc.totalLen / mod);
                if (i < 100)
                {
                    ResetProgressBar(0, i, 0);
                }
                modAct = (int)Math.Floor((float)toc.totalLen / 1000);
                modAct = (modAct | (maxBR - 1)) + 1;
                UpdateActionLabel("Rebuilding…");

                if (toc.totalLen > maxImageSize || toc.totalLen < 0)
                {
                    errorText = "The resulting image is too large";
                    error     = true;
                }

                idx = 3;

                if (!error)
                {
                    for (i = 3; i < toc.fils.Count; i++)
                    {
                        if (!addressRebuild)
                        {
                            idx = i;
                        }

                        if (!toc.fils[i].isDir)
                        {
                            fi = new sio.FileInfo(toc.fils[idx].path);
                            if (!fi.Exists)
                            {
                                errorText = string.Format("File '{0}' not found", fi.FullName);
                                error     = true;
                                break;
                            }
                            fsr = new sio.FileStream(toc.fils[idx].path, sio.FileMode.Open, sio.FileAccess.Read, sio.FileShare.Read);
                            brr = new sio.BinaryReader(fsr, ste.Default);

                            if (!dataStartPositioned)
                            {
                                m = filesMod - ((int)fsw.Position % filesMod);
                                for (j = 0; j < m; j++)
                                {
                                    bww.Write((byte)0);
                                }
                                bytesWritten += maxBR - (bytesWritten % maxBR);
                                m             = (int)fsw.Position;
                                b             = new byte[maxBR];
                                for (j = m; j < toc.dataStart; j += maxBR)
                                {
                                    fsw.Write(b, 0, maxBR);
                                    bytesWritten += maxBR;

                                    if (bytesWritten % modAct == 0)
                                    {
                                        UpdateActionLabel(string.Format("Rebuilding: {0}/{1} bytes written", bytesWritten, toc.totalLen));
                                    }

                                    if (bytesWritten % mod == 0)
                                    {
                                        UpdateProgressBar(1);
                                    }

                                    if (escapePressed)
                                    {
                                        if (ShowMTMBox("Cancel current process?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, DialogResult.Yes))
                                        {
                                            stopCurrProc = true;
                                        }
                                    }

                                    if (stopCurrProc)
                                    {
                                        break;
                                    }
                                }
                                if (!stopCurrProc)
                                {
                                    fsw.Write(b, 0, toc.dataStart % maxBR);
                                    curBR               = maxBR;
                                    bytesWritten        = toc.dataStart + (maxBR - (toc.dataStart % maxBR)) - maxBR;
                                    fsw.Position        = toc.dataStart;
                                    dataStartPositioned = true;
                                }
                            }

                            if (stopCurrProc)
                            {
                                break;
                            }

                            if (fsw.Position != toc.fils[idx].pos)
                            {
                                m = toc.fils[idx].pos - (int)fsw.Position;
                                for (j = 0; j < m; j++)
                                {
                                    bww.Write((byte)0);
                                }
                                curBR        -= m;
                                bytesWritten += m;
                            }

                            if (curBR < 0)
                            {
                                errorText = "Oooopps)\r\nPlease mail me info about this image";
                                error     = true;
                                break;
                            }

                            while (fsr.Position < fsr.Length)
                            {
                                b             = brr.ReadBytes(curBR);
                                temBR         = b.Length;
                                bytesWritten += temBR;
                                if (temBR == curBR)
                                {
                                    curBR = maxBR;

                                    if (bytesWritten % modAct == 0)
                                    {
                                        UpdateActionLabel(string.Format("Rebuilding: {0}/{1} bytes written", bytesWritten, toc.totalLen));
                                        if (stopCurrProc)
                                        {
                                            break;
                                        }
                                    }

                                    if (bytesWritten % mod == 0)
                                    {
                                        UpdateProgressBar(1);
                                    }
                                }
                                else
                                {
                                    curBR -= temBR;
                                }
                                bww.Write(b);

                                if (escapePressed)
                                {
                                    if (ShowMTMBox("Cancel current process?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, DialogResult.Yes))
                                    {
                                        stopCurrProc = true;
                                    }
                                }
                            }

                            brr.Close();
                            fsr.Close();

                            if (stopCurrProc)
                            {
                                break;
                            }

                            if (addressRebuild)
                            {
                                idx = toc.fils[i].nextIdx;
                            }

                            if (i == 5)
                            {
                                dataStartPositioned = false;
                            }
                        }
                    }
                }

                m = filesMod - ((int)fsw.Position % filesMod);
                for (i = 0; i < m; i++)
                {
                    bww.Write((byte)0);
                }

                fi = new sio.FileInfo(toc.fils[5].path);
                if (fi.Exists)
                {
                    sio.File.Delete(toc.fils[5].path);
                    toc.fils[5].path = tocPath;
                }
            }
            catch (Exception ex)
            {
                error     = true;
                errorText = ex.Message;
            }
            if (!error && !stopCurrProc)
            {
                if (appendImage)
                {
                    fsw.SetLength(maxImageSize); //1459978240
                }
            }
            if (bww != null)
            {
                bww.Close();
            }
            if (fsw != null)
            {
                fsw.Close();
            }
            if (brr != null)
            {
                brr.Close();
            }
            if (brw != null)
            {
                brw.Close();
            }
            if (fsr != null)
            {
                fsr.Close();
            }
            if (br != null)
            {
                br.Close();
            }
            if (bw != null)
            {
                bw.Close();
            }
            if (ms != null)
            {
                ms.Close();
            }

            ResetControlsRebuild(error, errorText);

            isRebuilding = false;
            stopCurrProc = false;
        }
Example #53
0
 public void Reset()
 {
     LF.SetLength(0);
     LF.Position = 0;
     LF.Flush(true);
 }
Example #54
0
 public void SetLength(long value)
 {
     fileStream.SetLength(value);
 }
Example #55
0
 public void Backup()
 {
     try
     {
         //file.bak01, file.bak02... file.bakNN where NN is the latest
         string fn = string.Format("{0}.bak{1}", FileName, Core.Settings.Default.DatabaseBackupMaxBackups.ToString("00"));
         if (File.Exists(fn))
         {
             //ok, maximum reached
             //delete the oldest and rename the others
             fn = string.Format("{0}.bak{1}", FileName, 1.ToString("00"));
             if (File.Exists(fn))
             {
                 File.Delete(fn);
             }
             for (int i = 1; i < Core.Settings.Default.DatabaseBackupMaxBackups; i++)
             {
                 string fns = string.Format("{0}.bak{1}", FileName, (i + 1).ToString("00"));
                 string fnd = string.Format("{0}.bak{1}", FileName, i.ToString("00"));
                 if (File.Exists(fns))
                 {
                     File.Move(fns, fnd);
                 }
             }
             fn = string.Format("{0}.bak{1}", FileName, Core.Settings.Default.DatabaseBackupMaxBackups.ToString("00"));
         }
         else
         {
             //look for latest
             int i = 1;
             fn = string.Format("{0}.bak{1}", FileName, i.ToString("00"));
             while (File.Exists(fn))
             {
                 i++;
                 fn = string.Format("{0}.bak{1}", FileName, i.ToString("00"));
             }
         }
         DateTime nextUpdate = DateTime.Now.AddSeconds(1);
         using (Utils.ProgressBlock prog = new ProgressBlock("CreatingBackup", "CreatingBackup", 100, 0))
         {
             using (System.IO.FileStream fs = File.OpenWrite(fn))
             {
                 int    read;
                 byte[] buffer = new byte[10 * 1024 * 1024];
                 fs.SetLength(this.FileStream.Length);
                 this.FileStream.Position = 0;
                 while (this.FileStream.Position < this.FileStream.Length)
                 {
                     read = this.FileStream.Read(buffer, 0, buffer.Length);
                     fs.Write(buffer, 0, read);
                     if (DateTime.Now >= nextUpdate)
                     {
                         prog.Update("Loading", 100, (int)(100.0 * (double)this.FileStream.Position / (double)this.FileStream.Length));
                         nextUpdate = DateTime.Now.AddSeconds(1);
                     }
                 }
             }
             MostRecentBackupDate     = File.GetCreationTime(fn);
             this.FileStream.Position = 0;
         }
     }
     catch (Exception e)
     {
         Core.ApplicationData.Instance.Logger.AddLog(this, e);
     }
 }
Example #56
0
 public void SetLength(int length)
 {
     _stream?.SetLength(length);
 }
Example #57
0
        // check objects change state,
        private static bool CheckChangeState()
        {
            bool             changeState   = false;
            List <TouchData> touchDataList = Touch.GetData(0);

            // button.
            if (button0.TouchDown(touchDataList))
            {
                if (true == System.IO.File.Exists(@SAVE_FILE))
                {
                    using (System.IO.FileStream hStream = System.IO.File.Open(@SAVE_FILE, FileMode.Open)) {
                        if (hStream != null)
                        {
                            long size = hStream.Length;
                            inputData = new byte[size];
                            hStream.Read(inputData, 0, (int)size);
                            inputDataSize = (int)size;
                            string label = System.Text.Encoding.Unicode.GetString(inputData);
                            inputTextButton.SetText(label);
                            hStream.Close();
                            eventAction = EVENT_LOAD;
                        }
                    }
                }
            }

            else if (button1.TouchDown(touchDataList))
            {
                if (inputDataSize > 0)
                {
                    using (System.IO.FileStream hStream = System.IO.File.Open(@SAVE_FILE, FileMode.Create)) {
                        hStream.SetLength((int)inputDataSize);
                        hStream.Write(inputData, 0, (int)inputDataSize);
                        hStream.Close();
                        isFileExist = true;
                        eventAction = EVENT_WRITE;
                    }
                }
            }

            else if (button2.TouchDown(touchDataList))
            {
                if (true == System.IO.File.Exists(@SAVE_FILE))
                {
                    System.IO.File.Delete(@SAVE_FILE);
                    inputTextButton.SetText(" ");
                    inputDataSize = 0;
                    inputData     = null;
                    isFileExist   = false;
                    eventAction   = EVENT_DELETE;
                }
            }


            // input dialog.
            if (inputTextButton.TouchDown(touchDataList))
            {
                if (dialog == null)
                {
                    dialog      = new TextInputDialog();
                    dialog.Text = inputTextButton.Label;
                    dialog.Open();
                }
                return(true);
            }

            if (dialog != null)
            {
                if (dialog.State == CommonDialogState.Finished)
                {
                    if (dialog.Result == CommonDialogResult.OK)
                    {
                        string setLabelStr;
                        int    i;

                        int len = dialog.Text.Length;

                        if (len > MAX_INPUT_CHARACTOR)
                        {
                            len = MAX_INPUT_CHARACTOR;
                        }

                        setLabelStr = dialog.Text.Substring(0, len);

                        inputTextButton.Label = setLabelStr;

                        byte[] byteArray0 = System.Text.Encoding.Unicode.GetBytes(setLabelStr);
                        inputData = new byte[byteArray0.Length];
                        for (i = 0; i < byteArray0.Length; i++)
                        {
                            inputData[i] = byteArray0[i];
                        }

                        inputDataSize = byteArray0.Length;

                        changeState = true;
                    }
                    dialog.Dispose();
                    dialog = null;
                }
            }

            return(changeState);
        }
Example #58
0
 /// <summary>
 /// Truncates an existing file to a specified length
 /// </summary>
 /// <param name="fileInfo">File to truncate</param>
 /// <param name="length">New length of file</param>
 private void TruncateFile(IO.FileInfo fileInfo, int length)
 {
     IO.FileStream fstream = fileInfo.OpenWrite();
     fstream.SetLength(length);
     fstream.Close();
 }
Example #59
0
        //public static A trySafe<A>(A valueIfThrows,  Func<A> f )
        //{
        //    try
        //    {
        //        return f.Invoke();
        //    }
        //    catch (Exception e)
        //    {
        //        CrashReportFsharp.sendSilentCrashIfEnoughTimePassed2(
        //    }
        //}

        public static void appendToXmlCore(int maxNumOperationsInXml, string xmlLogPath, XElement xel, string rootElementName)
        {
            var parentDir = System.IO.Path.GetDirectoryName(xmlLogPath);

            if (!io.Directory.Exists(parentDir))
            {
                io.Directory.CreateDirectory(parentDir);
            }

            io.FileStream fs;
            bool          xmlWasCreated;
            {
                try
                {
                    fs            = new io.FileStream(xmlLogPath, io.FileMode.Open, io.FileAccess.ReadWrite);
                    xmlWasCreated = false;
                }
                catch (io.FileNotFoundException)
                {
                    fs            = new io.FileStream(xmlLogPath, io.FileMode.Create, io.FileAccess.ReadWrite);
                    xmlWasCreated = true;
                }
            }



            var xdoc = new Func <XDocument>(() =>
            {
                var createNew = new Func <XDocument>(() =>
                {
                    var root = new XElement(rootElementName, xel);
                    return(new XDocument(root));
                });

                if (xmlWasCreated)
                {
                    return(createNew());
                }
                else
                {
                    try
                    {
                        var xdoc2 = XDocument.Load(fs);
                        xdoc2.Root.Add(xel);
                        return(xdoc2);
                    }
                    catch (System.Xml.XmlException)
                    {
                        return(createNew());
                    }
                }
            })();

            {
                var count = xdoc.Root.Elements().Count();
                if (count > maxNumOperationsInXml)
                {
                    var howManyToRemove  = count - maxNumOperationsInXml;
                    var elementsToRemove = xdoc.Root.Elements().Take(howManyToRemove).ToList();
                    foreach (var el in elementsToRemove)
                    {
                        el.Remove();
                    }
                }
            }

            {
                fs.SetLength(0);
                xdoc.Save(fs);
                fs.Dispose();
            }
        }