当前位置: 首页>>代码示例>>C#>>正文


C# FileStream.SetLength方法代码示例

本文整理汇总了C#中System.IO.FileStream.SetLength方法的典型用法代码示例。如果您正苦于以下问题:C# FileStream.SetLength方法的具体用法?C# FileStream.SetLength怎么用?C# FileStream.SetLength使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.FileStream的用法示例。


在下文中一共展示了FileStream.SetLength方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: FlushSetLengthAtEndOfBuffer

        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);
            }
        }
开发者ID:Rayislandstyle,项目名称:corefx,代码行数:35,代码来源:Buffering_regression.cs

示例2: GenerateBackups

        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);

            }
        }
开发者ID:jwarnes,项目名称:backupGen,代码行数:30,代码来源:Generator.cs

示例3: InvalidLengths

 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));
     }
 }
开发者ID:johnhhm,项目名称:corefx,代码行数:8,代码来源:SetLength.cs

示例4: SetLengthDisposedThrows

 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));
     }
 }
开发者ID:johnhhm,项目名称:corefx,代码行数:11,代码来源:SetLength.cs

示例5: WriteLog

        /// <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();
        }
开发者ID:ywxyn,项目名称:wtg-assistant,代码行数:35,代码来源:WriteLog.cs

示例6: FileStreamUnbufferedSequentialWrite

        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);
        }
开发者ID:jdauie,项目名称:cloudae,代码行数:26,代码来源:FileStreamUnbufferedSequentialWrite.cs

示例7: SendButton_Click

        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);
        }
开发者ID:JessicaMaxey,项目名称:Networks,代码行数:26,代码来源:ClientForm.cs

示例8: Main

		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);
			}
		}
开发者ID:avonwyss,项目名称:bsn-goldparser,代码行数:29,代码来源:Program.cs

示例9: writeprogress_FormClosing

        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());
            }

        }
开发者ID:YushanSUN,项目名称:wtg-assistant,代码行数:35,代码来源:WriteProgress.cs

示例10: LocateLocalFile

        /// <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;
        }
开发者ID:HiznyakNikita,项目名称:DownloadsManager,代码行数:33,代码来源:LocalFilesHelper.cs

示例11: MemoryMappedFileCheckpoint

        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();
            }
        }
开发者ID:EventStore,项目名称:EventStore,代码行数:28,代码来源:MemoryMappedFileCheckpoint.cs

示例12: WriteThroughFileCheckpoint

        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();
        }
开发者ID:Kristinn-Stefansson,项目名称:EventStore,代码行数:28,代码来源:WriteThroughFileCheckpoint.cs

示例13: DesDecrypt

        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();
        }
开发者ID:gettogether,项目名称:common-object,代码行数:28,代码来源:SecretHelper.cs

示例14: Logger

        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;
                }
            }
        }
开发者ID:ChristianKapfhammer,项目名称:SPLConqueror,代码行数:28,代码来源:Logger.cs

示例15: AllocateFile

        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
                };
        }
开发者ID:AccessMartinD,项目名称:Labo.DownloadManager,代码行数:28,代码来源:TempFileAllocator.cs


注:本文中的System.IO.FileStream.SetLength方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。