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


C# FileStream.SetLength方法代码示例

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


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

示例1: Export

 public void Export(string filePath)
 {
     FileStream outStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
     outStream.SetLength(Length);
     using (FileMap map = FileMap.FromStream(outStream))
         Win32.MoveMemory(map.Address, Address, (uint)Length);
 }
开发者ID:soneek,项目名称:Sm4sh-Tools,代码行数:7,代码来源:DataSource.cs

示例2: CreateSharedBackingObject

        private static FileStream CreateSharedBackingObject(
            Interop.libc.MemoryMappedProtections protections, long capacity,
            out string mapName, out SafeMemoryMappedFileHandle.FileStreamSource fileStreamSource)
        {
            // The POSIX shared memory object name must begin with '/'.  After that we just want something short and unique.
            mapName = "/" + MemoryMapObjectFilePrefix + Guid.NewGuid().ToString("N");
            fileStreamSource = SafeMemoryMappedFileHandle.FileStreamSource.ManufacturedSharedMemory;

            // Determine the flags to use when creating the shared memory object
            Interop.libc.OpenFlags flags = (protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 ?
                Interop.libc.OpenFlags.O_RDWR :
                Interop.libc.OpenFlags.O_RDONLY;
            flags |= Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_EXCL; // CreateNew

            // Determine the permissions with which to create the file
            Interop.libc.Permissions perms = default(Interop.libc.Permissions);
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_READ) != 0)
                perms |= Interop.libc.Permissions.S_IRUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0)
                perms |= Interop.libc.Permissions.S_IWUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_EXEC) != 0)
                perms |= Interop.libc.Permissions.S_IXUSR;

            // Create the shared memory object. Then enlarge it to the requested capacity.
            int fd;
            Interop.CheckIo(fd = Interop.libc.shm_open(mapName, flags, (int)perms), mapName);
            SafeFileHandle fileHandle = new SafeFileHandle((IntPtr)fd, ownsHandle: true);

            // Wrap the handle in a stream and return it.
            var fs = new FileStream(fileHandle, TranslateProtectionsToFileAccess(protections));
            fs.SetLength(capacity);
            return fs;
        }
开发者ID:jsalvadorp,项目名称:corefx,代码行数:33,代码来源:MemoryMappedFile.Linux.cs

示例3: CreateSharedBackingObject

        private static FileStream CreateSharedBackingObject(Interop.libc.MemoryMappedProtections protections, long capacity)
        {
            Directory.CreateDirectory(s_tempMapsDirectory);
            string path = Path.Combine(s_tempMapsDirectory, Guid.NewGuid().ToString("N"));
            
            FileAccess access =
                (protections & (Interop.libc.MemoryMappedProtections.PROT_READ | Interop.libc.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
                (protections & (Interop.libc.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
                FileAccess.Read;

            // Create the backing file, then immediately unlink it so that it'll be cleaned up when no longer in use.
            // Then enlarge it to the requested capacity.
            const int DefaultBufferSize = 0x1000;
            var fs = new FileStream(path, FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), FileShare.ReadWrite, DefaultBufferSize);
            try
            {
                Interop.CheckIo(Interop.Sys.Unlink(path));
                fs.SetLength(capacity);
            }
            catch
            {
                fs.Dispose();
                throw;
            }
            return fs;
        }
开发者ID:nblumhardt,项目名称:corefx,代码行数:26,代码来源:MemoryMappedFile.Unix.BackingObject_File.cs

示例4: EncryptData

	private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
	 {
	     //Create the file streams to handle the input and output files.
	     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
	     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
	     fout.SetLength(0);

	     //Create variables to help with read and write.
	     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
	     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.

	     SymmetricAlgorithm des = new DESCryptoServiceProvider();
         des.Padding = PaddingMode.PKCS7;
	     CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

	     Console.WriteLine("Encrypting...");

	     //Read from the input file, then encrypt and write to the output file.
	     while(rdlen < totlen)
	     {
	         len = fin.Read(bin, 0, 100);
	         encStream.Write(bin, 0, len);
	         rdlen = rdlen + len;
             Console.WriteLine("{0} bytes processed", rdlen);
         }
	     encStream.Close();
    }
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:29,代码来源:EncDecFileScn.cs

示例5: CreateCore

        private static unsafe SafeMemoryMappedFileHandle CreateCore(
            FileStream fileStream, string mapName, 
            HandleInheritability inheritability, MemoryMappedFileAccess access, 
            MemoryMappedFileOptions options, long capacity)
        {
            if (mapName != null)
            {
                // Named maps are not supported in our Unix implementation.  We could support named maps on Linux using 
                // shared memory segments (shmget/shmat/shmdt/shmctl/etc.), but that doesn't work on OSX by default due
                // to very low default limits on OSX for the size of such objects; it also doesn't support behaviors
                // like copy-on-write or the ability to control handle inheritability, and reliably cleaning them up
                // relies on some non-conforming behaviors around shared memory IDs remaining valid even after they've
                // been marked for deletion (IPC_RMID).  We could also support named maps using the current implementation
                // by not unlinking after creating the backing store, but then the backing stores would remain around
                // and accessible even after process exit, with no good way to appropriately clean them up.
                // (File-backed maps may still be used for cross-process communication.)
                throw CreateNamedMapsNotSupportedException();
            }

            bool ownsFileStream = false;
            if (fileStream != null)
            {
                // This map is backed by a file.  Make sure the file's size is increased to be
                // at least as big as the requested capacity of the map.
                if (fileStream.Length < capacity)
                {
                    try
                    {
                        fileStream.SetLength(capacity);
                    }
                    catch (ArgumentException exc)
                    {
                        // If the capacity is too large, we'll get an ArgumentException from SetLength, 
                        // but on Windows this same condition is represented by an IOException.
                        throw new IOException(exc.Message, exc);
                    }
                }
            }
            else
            {
                // This map is backed by memory-only.  With files, multiple views over the same map
                // will end up being able to share data through the same file-based backing store;
                // for anonymous maps, we need a similar backing store, or else multiple views would logically 
                // each be their own map and wouldn't share any data.  To achieve this, we create a backing object
                // (either memory or on disk, depending on the system) and use its file descriptor as the file handle.  
                // However, we only do this when the permission is more than read-only.  We can't change the size 
                // of an object that has read-only permissions, but we also don't need to worry about sharing
                // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views
                // will always see zero and can't change that.  In that case, we just use the built-in anonymous support of
                // the map by leaving fileStream as null.
                Interop.libc.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false);
                if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0)
                {
                    ownsFileStream = true;
                    fileStream = CreateSharedBackingObject(protections, capacity);
                }
            }

            return new SafeMemoryMappedFileHandle(fileStream, ownsFileStream, inheritability, access, options, capacity);
        }
开发者ID:nuskarthik,项目名称:corefx,代码行数:60,代码来源:MemoryMappedFile.Unix.cs

示例6: Clear

 /// <summary>
 /// 清空一个文件内容
 /// </summary>
 /// <param name="fileName"></param>
 public static void Clear(string fileName)
 {
     if (File.Exists(fileName) == true)
     {
         using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
         {
             fileStream.SetLength(0);
             fileStream.Close();
         }
     }
 }
开发者ID:renshengqiang,项目名称:UnityUtil,代码行数:15,代码来源:FileUtil.cs

示例7: SetPositionThenWrite

 public void SetPositionThenWrite()
 {
     string path = GetTestFilePath();
     using (var fileStream = new FileStream(path, FileMode.Create))
     {
         fileStream.SetLength(100);
         fileStream.Position = 100;
         var writer = new StreamWriter(fileStream);
         writer.Write("four");
         writer.Flush();
     }
     var testFile = new FileInfo(path);
     Assert.Equal(104, testFile.Length);
 }
开发者ID:neris,项目名称:corefx,代码行数:14,代码来源:Length.cs

示例8: CreateCore

        private static unsafe SafeMemoryMappedFileHandle CreateCore(
            FileStream fileStream, string mapName, 
            HandleInheritability inheritability, MemoryMappedFileAccess access, 
            MemoryMappedFileOptions options, long capacity)
        {
            if (mapName != null)
            {
                // TODO: We currently do not support named maps.  We could possibly support 
                // named maps in the future by using shm_open / shm_unlink, as we do for
                // giving internal names to anonymous maps.  Issues to work through will include 
                // dealing with permissions, passing information from the creator of the 
                // map to another opener of it, etc.
                throw CreateNamedMapsNotSupportedException();
            }

            var fileStreamSource = SafeMemoryMappedFileHandle.FileStreamSource.Provided;
            if (fileStream != null)
            {
                // This map is backed by a file.  Make sure the file's size is increased to be
                // at least as big as the requested capacity of the map.
                if (fileStream.Length < capacity)
                {
                    fileStream.SetLength(capacity);
                }
            }
            else
            {
                // This map is backed by memory-only.  With files, multiple views over the same map
                // will end up being able to share data through the same file-based backing store;
                // for anonymous maps, we need a similar backing store, or else multiple views would logically 
                // each be their own map and wouldn't share any data.  To achieve this, we create a backing object
                // (either memory or on disk, depending on the system) and use its file descriptor as the file handle.  
                // However, we only do this when the permission is more than read-only.  We can't change the size 
                // of an object that has read-only permissions, but we also don't need to worry about sharing
                // views over a read-only, anonymous, memory-backed map, because the data will never change, so all views
                // will always see zero and can't change that.  In that case, we just use the built-in anonymous support of
                // the map by leaving fileHandle as null.
                Interop.libc.MemoryMappedProtections protections = MemoryMappedView.GetProtections(access, forVerification: false);
                if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 && capacity > 0)
                {
                    fileStream = CreateSharedBackingObject(protections, capacity, out mapName, out fileStreamSource);
                }
            }

            return new SafeMemoryMappedFileHandle(mapName, fileStream, fileStreamSource, inheritability, access, options, capacity);
        }
开发者ID:jsalvadorp,项目名称:corefx,代码行数:46,代码来源:MemoryMappedFile.Unix.cs

示例9: CreateSharedBackingObject

        private static FileStream CreateSharedBackingObject(Interop.libc.MemoryMappedProtections protections, long capacity)
        {
            string path = TmpPathPrefix + Guid.NewGuid().ToString("N") + ".tmp";

            FileAccess access =
                (protections & (Interop.libc.MemoryMappedProtections.PROT_READ | Interop.libc.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
                (protections & (Interop.libc.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
                FileAccess.Read;

            // Create the backing file, then immediately unlink it so that it'll be cleaned up when no longer in use.
            // Then enlarge it to the requested capacity.
            const int DefaultBufferSize = 0x1000;
            var fs = new FileStream(path, FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), FileShare.ReadWrite, DefaultBufferSize);
            Interop.CheckIo(Interop.libc.unlink(path));
            fs.SetLength(capacity);
            return fs;
        }
开发者ID:johnhhm,项目名称:corefx,代码行数:17,代码来源:MemoryMappedFile.Unix.BackingObject_File.cs

示例10: Init

    private void Init(string ioPath, ref HashSet<string> refHashSet, bool isMd5Mode)
    {
        _isMD5 = isMd5Mode;
        _hashSet = refHashSet;

        if (File.Exists(ioPath))
        {
            using (var readStream = new FileStream(ioPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
            {
                // Read
                var sb = new StringBuilder();
                var sLength = readStream.Length;
                var lastNewlinePos = 0L;
                while (readStream.Position < sLength)
                {
                    var c = (char)readStream.ReadByte();
                    if (c == '\n')
                    {
                        var getStr = sb.ToString().Trim();
                        _hashSet.Add(getStr); // 过滤换行符 '\r'等
                        sb.Length = 0; // clear
                        lastNewlinePos = readStream.Position;
                    }
                    else
                    {
                        sb.Append(c);
                    }
                }

                if (lastNewlinePos != readStream.Position)
                {
                    // 抹掉最后一行!
                    // 最后一行,故意忽略掉,为什么?
                    // 因为上次程序有可能写到一半中途退出!  造成最后一行写入错误!超坑的!
                    readStream.SetLength(lastNewlinePos);  // 拦截到换行处
                }
            }  
        }
        _appendStream = new FileStream(ioPath, FileMode.Append, FileAccess.Write, FileShare.Read);
        _writer = new StreamWriter(_appendStream);

        _writer.AutoFlush = true; // 自动刷新, 每一次都是一个写入,会降低系统性能,但大大增加可靠性
    }
开发者ID:henry-yuxi,项目名称:CosmosEngine,代码行数:43,代码来源:CFileCacheList.cs

示例11: CreateSharedBackingObject

        private static FileStream CreateSharedBackingObject(
            Interop.libc.MemoryMappedProtections protections, long capacity,
            out string mapName, out SafeMemoryMappedFileHandle.FileStreamSource fileHandleSource)
        {
            mapName = MemoryMapObjectFilePrefix + Guid.NewGuid().ToString("N") + ".tmp";
            fileHandleSource = SafeMemoryMappedFileHandle.FileStreamSource.ManufacturedFile;

            FileAccess access =
                (protections & (Interop.libc.MemoryMappedProtections.PROT_READ | Interop.libc.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.ReadWrite :
                (protections & (Interop.libc.MemoryMappedProtections.PROT_WRITE)) != 0 ? FileAccess.Write :
                FileAccess.Read;

            const int DefaultBufferSize = 0x1000;
            var fs = new FileStream(Path.Combine(Path.GetTempPath(), mapName),
                FileMode.CreateNew, TranslateProtectionsToFileAccess(protections), FileShare.ReadWrite,
                DefaultBufferSize, FileOptions.DeleteOnClose);
            fs.SetLength(capacity);
            return fs;
        }
开发者ID:jsalvadorp,项目名称:corefx,代码行数:19,代码来源:MemoryMappedFile.OSX.cs

示例12: Logging

    //-----------------------------------------------------------------------------
    private Logging(string filePath, string fileName)
    {
        string userPath;

        if (filePath != null)
            userPath = string.Copy(filePath);
        else
            userPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        if (userPath.Length > 0)
        {
            userPath += "\\" + fileName;
            fStream = File.Open(userPath, FileMode.OpenOrCreate);
            //Now clear the file
            fStream.SetLength(0);
            fStream.Flush();
            isOpen = true;
        }
        else
            fStream = null;
    }
开发者ID:RandomCache,项目名称:LightningBug,代码行数:22,代码来源:Logging.cs

示例13: SaveItemInfo

    private void SaveItemInfo(Room room)
    {
        Level level = new Level();
        level.Rows = room.Rows;
        level.Columns = room.Columns;

        level.Cells = new Assets.Scripts.Data.Cell[room.Rows][];
        for(int i = 0; i < room.Rows; i++)
        {
            level.Cells[i] = new Assets.Scripts.Data.Cell[room.Columns];
        }

        foreach(var child in room.GetComponentsInChildren<Cell>())
        {
            level.Cells[child.CellData.I][child.CellData.J] = child.CellData;
        }

        level.Walls = new Assets.Scripts.Data.Wall[2][];
        level.Walls[0] = new Assets.Scripts.Data.Wall[room.Rows];
        level.Walls[1] = new Assets.Scripts.Data.Wall[room.Columns];

        foreach(var child in room.GetComponentsInChildren<Wall>())
        {
            level.Walls[child.WallData.I][child.WallData.J] = child.WallData;
        }

        var encoding = Encoding.GetEncoding("UTF-8");
        using(var file = new FileStream(Levels[selectedIndex], FileMode.OpenOrCreate))
        {
            file.SetLength(0);
            var serializer = new XmlSerializer(typeof(Level));
            using(StreamWriter writer = new StreamWriter(file, encoding))
                serializer.Serialize(writer, level);
        }
    }
开发者ID:SealTV,项目名称:test_game,代码行数:35,代码来源:RoomEditor.cs

示例14: writeSectionComment

	// 以FileStream方式,在写ini文件指写Section的注释
	public void writeSectionComment(string Section, string Comment)
	{
		//防止文本字符中有特殊字符。必须用Encoding.Default
		StreamReader reader = new StreamReader(FileName, Encoding.Default);

		String a = reader.ReadToEnd();
		reader.Close();

		int index = a.IndexOf(Section);
		if (index != -1)
		{
			a = a.Insert(index, replaceBadCharOfFileName(Comment + "\r\n"));

			FileStream stream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
			stream.Seek(0, SeekOrigin.Begin);
			stream.SetLength(0);
			StreamWriter writer = new StreamWriter(stream, Encoding.Default);
			writer.Write(a);
			writer.Close();
			stream.Close();
		}
		else
		{
			Trace.WriteLine(string.Format("Warning: No section [{0}], in DrvCfg.ini File.", Section));
		}
	}
开发者ID:gfxmode,项目名称:LIB,代码行数:27,代码来源:IniHandler.cs

示例15: ConvertToScatteringStore

        /// <summary>
        /// Given a file, this will convert to a scattering file store with files 
        /// no larger than the maximum slice size.
        /// </summary>
        /// <param name="f"></param>
        public void ConvertToScatteringStore(string f)
        {
            const int BUFFER_SIZE = 65536;

            FileStream src = new FileStream(f, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            long file_size = new FileInfo(f).Length;
            long current_p = max_slice_size;
            long to_write = System.Math.Min(file_size - current_p, max_slice_size);
            int write_to_part = 1;

            byte[] copy_buffer = new byte[BUFFER_SIZE];

            while (to_write > 0) {

                src.Seek(current_p, SeekOrigin.Begin);

                string to_f = SlicePartFile(write_to_part);
                if (File.Exists(to_f)) {
                    throw new IOException("Copy error, slice already exists.");
                }
                FileStream to_raf = new FileStream(to_f, FileMode.OpenOrCreate, FileAccess.Write);

                while (to_write > 0) {
                    int size_to_copy = (int)System.Math.Min(BUFFER_SIZE, to_write);

                    src.Read(copy_buffer, 0, size_to_copy);
                    to_raf.Write(copy_buffer, 0, size_to_copy);

                    current_p += size_to_copy;
                    to_write -= size_to_copy;
                }

                to_raf.Flush();
                to_raf.Close();

                to_write = System.Math.Min(file_size - current_p, max_slice_size);
                ++write_to_part;
            }

            // Truncate the source file
            if (file_size > max_slice_size) {
                src.Seek(0, SeekOrigin.Begin);
                src.SetLength(max_slice_size);
            }
            src.Close();
        }
开发者ID:erpframework,项目名称:cloudb,代码行数:51,代码来源:ScatteringStoreDataAccessor.cs


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