C# FileStream.Dispose的代码示例

通过代码示例来学习C# FileStream.Dispose方法

通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。


FileStream.Dispose是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的FileStream.Dispose() 已经帮大家高亮显示了,大家可以重点学习FileStream.Dispose() 方法的写法,从而快速掌握该方法的应用。

FileStream.Dispose的代码示例1 - TryWriteTempFile()

    using System.IO;

        public virtual bool TryWriteTempFile(
            ITracer tracer,
            Stream source,
            string tempFilePath,
            out long fileLength,
            out Task flushTask,
            bool throwOnError = false)
        {
            fileLength = 0;
            flushTask = null;
            try
            {
                Stream fileStream = null;

                try
                {
                    fileStream = this.fileSystem.OpenFileStream(
                        tempFilePath,
                        FileMode.OpenOrCreate,
                        FileAccess.Write,
                        FileShare.Read,
                        callFlushFileBuffers: false); // Any flushing to disk will be done asynchronously

                    StreamUtil.CopyToWithBuffer(source, fileStream);
                    fileLength = fileStream.Length;

                    if (this.Enlistment.FlushFileBuffersForPacks)
                    {
                        // Flush any data buffered in FileStream to the file system
                        fileStream.Flush();

                        // FlushFileBuffers using FlushAsync
                        // Do this last to ensure that the stream is not being accessed after it's been disposed
                        flushTask = fileStream.FlushAsync().ContinueWith((result) => fileStream.Dispose());
                    }
                }
                finally
                {
                    if (flushTask == null && fileStream != null)
                    {
                        fileStream.Dispose();
                    }
                }

                this.ValidateTempFile(tempFilePath, tempFilePath);
            }
            catch (Exception ex)
            {
                if (flushTask != null)
                {
                    flushTask.Wait();
                    flushTask = null;
                }

                this.CleanupTempFile(this.Tracer, tempFilePath);

                if (tracer != null)
                {
                    EventMetadata metadata = CreateEventMetadata(ex);
                    metadata.Add("tempFilePath", tempFilePath);
                    tracer.RelatedWarning(metadata, $"{nameof(this.TryWriteTempFile)}: Exception caught while writing temp file", Keywords.Telemetry);
                }

                if (throwOnError)
                {
                    throw;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:77,代码来源:GitObjects.cs

在TryWriteTempFile()方法中,FileStream的代码示例类中的Dispose的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Dispose的代码示例2 - YaraScanFile()

    using System.IO;

        public static List YaraScanFile(string fileName, bool verbose)
        {

            List beaconScanMatches = new List();

            using (var ctx = new YaraContext())
            {
                Rules rules = null;

                try
                {
                    using (Compiler compiler = new Compiler())
                    {
                        // Retrieve YARA rules from YaraRules static class and compile them for scanning
                        foreach (string rule in YaraRules.meterpreterRules)
                        {
                            compiler.AddRuleString(rule);
                        }

                        compiler.AddRuleString(YaraRules.cobaltStrikeRule);

                        rules = compiler.GetRules();
                    }

                    // Scanner and ScanResults do not need to be disposed.
                    var scanner = new Scanner();

                    List results = new List();

                    // If file size > 2GB, stream the file and use ScanMemory() on file chunks rather than reading the whole file via 
                    if (new FileInfo(fileName).Length < Int32.MaxValue)
                    {
                       results.AddRange(scanner.ScanFile(fileName, rules));
                    }
                    else
                    {
                        using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                        {
                            // Parse the file in 200MB chunks
                            int chunkSize = 1024 * 1024 * 200;
                            byte[] chunk = new byte[chunkSize];
                            int bytesRead = 0;
                            long bytesToRead = fileStream.Length;

                            while (bytesToRead != 0)
                            {
                                int n = fileStream.Read(chunk, 0, chunkSize);

                                if (n == 0)
                                {
                                    break;
                                }

                                // Yara scan the file chunk and add any results to the list
                                var scanResults = scanner.ScanMemory(chunk, rules);

                                // Because the file is being scanned in chunks, match offsets are based on the start of the chunk. Need to add
                                // previous bytes read to the current match offsets
                                if (scanResults.Count > 0)
                                {
                                    foreach (ScanResult result in scanResults)
                                    {
                                        if (result.MatchingRule.Identifier.Contains("CobaltStrike"))
                                        {
                                            foreach (string key in result.Matches.Keys)
                                            {
                                                result.Matches[key][0].Offset += (ulong)bytesRead;
                                            }
                                            results.Add(result);
                                        }
                                    }
                                }

                                bytesRead += n;
                                bytesToRead -= n;
                                
                                // Shitty progress update
                                if (verbose && bytesRead > 0 && bytesRead <= fileStream.Length)
                                    Console.Write($"\r\tScanned {bytesRead} bytes of {fileStream.Length} byte file...");
                            }
                        }
                        if (verbose)
                            Console.WriteLine($"\r\tFinished scanning file: {fileName}\t\t\t");
                    }

                    beaconScanMatches = ParseScanResults(results);
                }
                finally
                {
                    // Rules and Compiler objects must be disposed.
                    if (rules != null) rules.Dispose();
                }

                return beaconScanMatches;
            }
        }
    

开发者ID:Apr4h,项目名称:CobaltStrikeScan,代码行数:98,代码来源:CobaltStrikeScan.cs

在YaraScanFile()方法中,FileStream的代码示例类中的Dispose的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Dispose的代码示例3 - ExecuteCoreAsync()

    using System.IO;

        protected override Task ExecuteCoreAsync()
        {
            // Make sure there's only one server with the same identity at a time.
            var serverMutexName = MutexName.GetServerMutexName(Pipe.Value());
            Mutex serverMutex = null;
            var holdsMutex = false;

            try
            {
                serverMutex = new Mutex(initiallyOwned: true, name: serverMutexName, createdNew: out holdsMutex);
            }
            catch (Exception ex)
            {
                // The Mutex constructor can throw in certain cases. One specific example is docker containers
                // where the /tmp directory is restricted. In those cases there is no reliable way to execute
                // the server and we need to fall back to the command line.
                // Example: https://github.com/dotnet/roslyn/issues/24124

                Error.Write($"Server mutex creation failed. {ex.Message}");

                return Task.FromResult(-1);
            }

            if (!holdsMutex)
            {
                // Another server is running, just exit.
                Error.Write("Another server already running...");
                return Task.FromResult(1);
            }

            FileStream pidFileStream = null;
            try
            {
                try
                {
                    // Write the process and pipe information to a file in a well-known location.
                    pidFileStream = WritePidFile();
                }
                catch (Exception ex)
                {
                    // Something happened when trying to write to the pid file. Log and move on.
                    ServerLogger.LogException(ex, "Failed to create PID file.");
                }

                TimeSpan? keepAlive = null;
                if (KeepAlive.HasValue() && int.TryParse(KeepAlive.Value(), out var result))
                {
                    // Keep alive times are specified in seconds
                    keepAlive = TimeSpan.FromSeconds(result);
                }

                var host = ConnectionHost.Create(Pipe.Value());

                var compilerHost = CompilerHost.Create();
                ExecuteServerCore(host, compilerHost, Cancelled, eventBus: null, keepAlive: keepAlive);
            }
            finally
            {
                serverMutex.ReleaseMutex();
                serverMutex.Dispose();
                pidFileStream?.Close();
            }

            return Task.FromResult(0);
        }
    

开发者ID:aspnet,项目名称:Razor,代码行数:67,代码来源:ServerCommand.cs

在ExecuteCoreAsync()方法中,FileStream的代码示例类中的Dispose的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Dispose的代码示例4 - OpenAsync()

    using System.IO;

		public override IAsyncOperation OpenAsync(FileAccessMode accessMode)
		{
			return AsyncInfo.Run((cancellationToken) => SafetyExtensions.Wrap(async () =>
			{
				bool rw = accessMode is FileAccessMode.ReadWrite;
				if (Path == containerPath)
				{
					if (backingFile is not null)
					{
						return await backingFile.OpenAsync(accessMode);
					}

					var file = NativeFileOperationsHelper.OpenFileForRead(containerPath, rw);
					return file.IsInvalid ? null : new FileStream(file, rw ? FileAccess.ReadWrite : FileAccess.Read).AsRandomAccessStream();
				}

				if (!rw)
				{
					SevenZipExtractor zipFile = await OpenZipFileAsync();
					if (zipFile is null || zipFile.ArchiveFileData is null)
					{
						return null;
					}

					//zipFile.IsStreamOwner = true;
					var entry = zipFile.ArchiveFileData.FirstOrDefault(x => System.IO.Path.Combine(containerPath, x.FileName) == Path);

					if (entry.FileName is not null)
					{
						var ms = new MemoryStream();
						await zipFile.ExtractFileAsync(entry.Index, ms);
						ms.Position = 0;
						return new NonSeekableRandomAccessStreamForRead(ms, entry.Size)
						{
							DisposeCallback = () => zipFile.Dispose()
						};
					}
					return null;
				}

				throw new NotSupportedException("Can't open zip file as RW");
			}, ((IPasswordProtectedItem)this).RetryWithCredentialsAsync));
		}
    

开发者ID:files-community,项目名称:Files,代码行数:45,代码来源:ZipStorageFile.cs

在OpenAsync()方法中,FileStream的代码示例类中的Dispose的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Dispose的代码示例5 - Output()

    using System.IO;

        public override int Output(IEnumerable source, BsonValue options)
        {
            var filename = GetOption(options, "filename")?.AsString ?? throw new LiteException(0, "Collection $file_json requires string as 'filename' or a document field 'filename'");
            var overwritten = GetOption(options, "overwritten", false).AsBoolean;
            var encoding = GetOption(options, "encoding", "utf-8").AsString;
            var delimiter = GetOption(options, "delimiter", ",").AsString[0];
            var header = GetOption(options, "header", true).AsBoolean;

            var index = 0;

            IList headerFields = null;
            FileStream fs = null;
            StreamWriter writer = null;

            try
            {
                foreach (var doc in source)
                {
                    if (index++ == 0)
                    {
                        fs = new FileStream(filename, overwritten ? FileMode.OpenOrCreate : FileMode.CreateNew);
                        writer = new StreamWriter(fs, Encoding.GetEncoding(encoding));

                        headerFields = doc.Keys.ToList();

                        // print file header
                        if (header)
                        {
                            var idxHeader = 0;

                            foreach (var elem in doc)
                            {
                                if (idxHeader++ > 0) writer.Write(delimiter);
                                writer.Write(elem.Key);
                            }

                            writer.WriteLine();
                        }
                    }
                    else
                    {
                        writer.WriteLine();
                    }

                    var idxValue = 0;

                    foreach(var field in headerFields)
                    {
                        var value = doc[field];

                        if (idxValue++ > 0) writer.Write(delimiter);

                        this.WriteValue(value, writer);
                    }
                }

                if (index > 0)
                {
                    writer.Flush();
                }
            }
            finally
            {
                if (writer != null) writer.Dispose();
                if (fs != null) fs.Dispose();
            }

            return index;
        }
    

开发者ID:mbdavid,项目名称:LiteDB,代码行数:71,代码来源:SysFileCsv.cs

在Output()方法中,FileStream的代码示例类中的Dispose的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Dispose的代码示例6 - Output()

    using System.IO;

        public override int Output(IEnumerable source, BsonValue options)
        {
            var filename = GetOption(options, "filename")?.AsString ?? throw new LiteException(0, "Collection $file_json requires string as filename or a document field 'filename'");
            var pretty = GetOption(options, "pretty", false).AsBoolean;
            var indent = GetOption(options, "indent", 4).AsInt32;
            var encoding = GetOption(options, "encoding", "utf-8").AsString;
            var overwritten = GetOption(options, "overwritten", false).AsBoolean;

            var index = 0;
            FileStream fs = null;
            StreamWriter writer = null;
            JsonWriter json = null;

            try
            {
                foreach (var doc in source)
                {
                    if (index++ == 0)
                    {
                        fs = new FileStream(filename, overwritten ? FileMode.OpenOrCreate : FileMode.CreateNew);
                        writer = new StreamWriter(fs, Encoding.GetEncoding(encoding));
                        json = new JsonWriter(writer)
                        {
                            Pretty = pretty,
                            Indent = indent
                        };

                        writer.WriteLine("[");
                    }
                    else
                    {
                        writer.WriteLine(",");
                    }

                    json.Serialize(doc);
                }

                if (index > 0)
                {
                    writer.WriteLine();
                    writer.Write("]");
                    writer.Flush();
                }
            }
            finally
            {
                if (writer != null) writer.Dispose();
                if (fs != null) fs.Dispose();
            }

            return index;
        }
    

开发者ID:mbdavid,项目名称:LiteDB,代码行数:54,代码来源:SysFileJson.cs

在Output()方法中,FileStream的代码示例类中的Dispose的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Dispose的代码示例7 - Seek()

    using System.IO;

        public override long Seek(long offset, SeekOrigin origin)
        {
            var position =
                origin == SeekOrigin.Begin ? offset :
                origin == SeekOrigin.Current ? _stream.Position + offset :
                _stream.Position - offset;

            // when offset pass limit first time, change current _stream from MemoryStrem to FileStream with TempFilename()
            if (position > _maxMemoryUsage && this.InMemory)
            {
                // create new filename if not passed on ctor (must be unique
                _filename = _filename ?? Path.Combine(Path.GetTempPath(), "litedb_" + Guid.NewGuid() + ".db");

                var file = new FileStream(_filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, PAGE_SIZE, FileOptions.RandomAccess);

                // copy data from memory to disk
                _stream.Position = 0;
                _stream.CopyTo(file);

                // dispose MemoryStream
                _stream.Dispose();

                // and replace with FileStream
                _stream = file;
            }

            return _stream.Seek(offset, origin);
        }
    

开发者ID:mbdavid,项目名称:LiteDB,代码行数:30,代码来源:TempStream.cs

在Seek()方法中,FileStream的代码示例类中的Dispose的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

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