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


C# FileStream.?.Close方法代码示例

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


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

示例1: GetBuildTime

        protected override DateTime? GetBuildTime()
        {
            if (!Configuration.UseBuildTime) return null;

            const int peHeaderOffset = 60;
            const int linkerTimestampOffset = 8;

            FileStream s = null;
            var b = new byte[2048];

            try
            {
                var filePath = GetFirstAssembly().Location;
                s = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                s.Read(b, 0, 2048);
            }
            finally
            {
                s?.Close();
            }

            var i = BitConverter.ToInt32(b, peHeaderOffset);
            var secondsSince1970 = BitConverter.ToInt32(b, i + linkerTimestampOffset);
            var dt = new DateTime(1970, 1, 1, 0, 0, 0);
            dt = dt.AddSeconds(secondsSince1970);
            dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours);

            return dt;
        }
开发者ID:Quilt4,项目名称:Quilt4Net,代码行数:29,代码来源:ApplicationInformation.cs

示例2: AddFlie

 public void AddFlie(string name, string filename)
 {
     if (!File.Exists(filename))
         throw new FileNotFoundException(filename);
     FileStream fs = null;
     try
     {
         fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
         var fileData = new byte[fs.Length];
         fs.Read(fileData, 0, fileData.Length);
         AddFlie(name, Path.GetFileName(filename), fileData, fileData.Length);
     }
     finally
     {
         fs?.Close();
     }
 }
开发者ID:devworker55,项目名称:Mammatus,代码行数:17,代码来源:MultipartForm.cs

示例3: WriteData

 // 二进制数据写入到文件
 public static bool WriteData(string path, byte[] data)
 {
     FileStream fs = null;
     try
     {
         fs = new FileStream(path, FileMode.Create);
         fs.Write(data, 0, data.Length);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message, e.Source, MessageBoxButton.OK, MessageBoxImage.Error);
         return false;
     }
     finally
     {
         fs?.Close();
     }
     return true;
 }
开发者ID:XXZZQQ,项目名称:RSDIP-A,代码行数:20,代码来源:ConvertWindow.xaml.cs

示例4: DownLoad

        public static void DownLoad(string FileName)
        {
            string filePath = MapPathFile(FileName);
            long chunkSize = 204800;
            byte[] buffer = new byte[chunkSize];
            FileStream stream = null;
            try
            {
                stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                var dataToRead = stream.Length;

                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
                HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());

                while (dataToRead > 0)
                {
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.Clear();
                        dataToRead -= length;
                    }
                    else
                    {
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("Error:" + ex.Message);
            }
            finally
            {
                stream?.Close();
                HttpContext.Current.Response.Close();
            }
        }
开发者ID:devworker55,项目名称:Mammatus,代码行数:41,代码来源:FileDown.cs

示例5: GenerateVCFile

        private static void GenerateVCFile()
        {
            var fileName = Arguments[Parameters.GenerateVC.TL()] != null
                               ? Arguments[Parameters.GenerateVC.TL()].First()
                               : "VersioningControl.xml";

            var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(VersionControlResource);
            if (stream == null)
            {
                throw new MissingManifestResourceException("A versioning control file cannot be created. The embedded resource is not found.");
            }

            FileStream file = null;
            try
            {
                file = new FileStream(fileName, FileMode.Create);
                var b = new byte[stream.Length + 1];
                stream.Read(b, 0, Convert.ToInt32(stream.Length));
                file.Write(b, 0, Convert.ToInt32(b.Length - 1));
                file.Flush();
            }
            catch (UnauthorizedAccessException ex)
            {
                throw new ProcessCommandException("A versioning control file cannot be created by unauthorized access.", ex);
            }
            catch (IOException ex)
            {
                throw new ProcessCommandException($"A versioning control file cannot be created by an unknown error.\n{ex.Message}", ex);
            }
            catch (ArgumentException ex)
            {
                throw new ProcessCommandException($"A versioning control file cannot be created.\n{ex.Message}", ex);
            }
            finally
            {
                file?.Close();
                stream?.Close();
            }
        }
开发者ID:manu-vilachan,项目名称:SemanticVersionManager,代码行数:39,代码来源:Program.cs

示例6: SaveFile

        public static bool SaveFile(string fileName, object toSerialize, System.Windows.Forms.IWin32Window owner)
        {
            FileStream outStream = null;
            bool saveOk = false;

            try
            {
                outStream = new FileStream(fileName, FileMode.Create);
                (new BinaryFormatter()).Serialize(outStream, toSerialize);

                outStream.Close();
                outStream = null;

                saveOk = true;
            }
            catch (IOException ex)
            {
                FormAlert.Alert(AlertType.FileErrorSave, owner, fileName, ex.Message);
            }
            finally
            {
                outStream?.Close();
            }

            return saveOk;
        }
开发者ID:Banner-Keith,项目名称:SpaceTrader,代码行数:26,代码来源:Functions.cs

示例7: LoadFile

        public static object LoadFile(string fileName, bool ignoreMissingFile, System.Windows.Forms.IWin32Window owner)
        {
            object obj = null;
            FileStream inStream = null;

            try
            {
                inStream = new FileStream(fileName, FileMode.Open);
                obj = (new BinaryFormatter()).Deserialize(inStream);
                inStream.Close();
                inStream = null;
            }
            catch (FileNotFoundException ex)
            {
                if (!ignoreMissingFile)
                    FormAlert.Alert(AlertType.FileErrorOpen, owner, fileName, ex.Message);
            }
            catch (IOException ex)
            {
                FormAlert.Alert(AlertType.FileErrorOpen, owner, fileName, ex.Message);
            }
            catch (System.Runtime.Serialization.SerializationException)
            {
                FormAlert.Alert(AlertType.FileErrorOpen, owner, fileName, Strings.FileFormatBad);
            }
            finally
            {
                inStream?.Close();
            }

            return obj;
        }
开发者ID:Banner-Keith,项目名称:SpaceTrader,代码行数:32,代码来源:Functions.cs

示例8: FileIsWriteLocked

        private static bool FileIsWriteLocked(string fileName)
        {
            Stream fileStream = null;

            if (!File.Exists(fileName))
            {
                // It can't be locked if it doesn't exist
                return false;
            }

            try
            {
                // Try to open for shared reading
                fileStream = new FileStream(fileName,
                    FileMode.Open,
                    FileAccess.Read,
                    FileShare.Read | FileShare.Delete);

                // If we can open it for shared reading, it is not write locked
                return false;
            }
            catch
            {
                return true;
            }
            finally
            {
                fileStream?.Close();
            }
        }
开发者ID:chcosta,项目名称:corefx,代码行数:30,代码来源:WriteFileContext.cs

示例9: ValidateWriteAccess

        // Validate that we can write to the file.  This will enforce the ACL's
        // on the file.  Since we do our moving of files to replace, this is 
        // nice to ensure we are not by-passing some security permission
        // that someone set (although that could bypass this via move themselves)
        //
        // Note: 1) This is really just a nice to have, since with directory permissions
        //          they could do the same thing we are doing
        //
        //       2) We are depending on the current behavior that if the file is locked 
        //          and we can not open it, that we will get an UnauthorizedAccessException
        //          and not the IOException.
        private void ValidateWriteAccess(string filename)
        {
            FileStream fs = null;

            try
            {
                // Try to open file for write access
                fs = new FileStream(filename,
                    FileMode.Open,
                    FileAccess.Write,
                    FileShare.ReadWrite);
            }
            catch (IOException)
            {
                // Someone else was using the file.  Since we did not get
                // the unauthorizedAccessException we have access to the file
            }
            finally
            {
                fs?.Close();
            }
        }
开发者ID:chcosta,项目名称:corefx,代码行数:33,代码来源:WriteFileContext.cs

示例10: SaveFile

 public void SaveFile(byte[] binData, string fileName, string fileType)
 {
     FileStream fileStream = null;
     MemoryStream m = new MemoryStream(binData);
     try
     {
         string savePath = HttpContext.Current.Server.MapPath("~/File/");
         if (!Directory.Exists(savePath))
         {
             Directory.CreateDirectory(savePath);
         }
         string File = savePath + fileName + fileType;
         fileStream = new FileStream(File, FileMode.Create);
         m.WriteTo(fileStream);
     }
     finally
     {
         m.Close();
         fileStream?.Close();
     }
 }
开发者ID:devworker55,项目名称:Mammatus,代码行数:21,代码来源:FileUp.cs

示例11: WriteToDisk

        static async Task WriteToDisk(HttpResponseMessage response, Uri uri, string filePath)
        {
            FileStream stream = null;
            try
            {
                stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
                await response.Content.CopyToAsync(stream);

            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error '{ex.Message}' when trying to fetch: {uri}");
            }
            finally
            {
                stream?.Close();
            }

        }
开发者ID:jchannon,项目名称:WebsiteScraper,代码行数:19,代码来源:Program.cs

示例12: UnmarshallXml

        public PinballXMenu UnmarshallXml(string filepath)
        {
            var menu = new PinballXMenu();

            if (!File.Exists(filepath)) {
                return menu;
            }
            Stream reader = null;
            try {
                var serializer = new XmlSerializer(typeof(PinballXMenu));
                reader = new FileStream(filepath, FileMode.Open);
                menu = serializer.Deserialize(reader) as PinballXMenu;

            } catch (Exception e) {
                _logger.Error(e, "Error parsing {0}: {1}", filepath, e.Message);
                _crashManager.Report(e, "xml");

            } finally {
                reader?.Close();
            }
            return menu;
        }
开发者ID:freezy,项目名称:vpdb-agent,代码行数:22,代码来源:MarshallManager.cs

示例13: Load

        public static DecisionBatch Load(string path)
        {
            DecisionBatch cls = null;
            FileStream fs = null;

            try
            {
                fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                var formatter = new BinaryFormatter();
                cls = (DecisionBatch)formatter.Deserialize(fs);
                cls.Id = NCls++;
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }
            finally
            {
                fs?.Close();
            }

            return cls;
        }
开发者ID:orlovk,项目名称:PtProject,代码行数:23,代码来源:DecisionBatch.cs

示例14: RetrieveLinkerTimestamp

        public static DateTime RetrieveLinkerTimestamp()
        {
            var filePath = Assembly.GetCallingAssembly().Location;
            const int peHeaderOffset = 60;
            const int linkerTimestampOffset = 8;
            var b = new byte[2048];
            Stream s = null;

            try
            {
                s = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                s.Read(b, 0, 2048);
            }
            finally
            {
                s?.Close();
            }

            var i = BitConverter.ToInt32(b, peHeaderOffset);
            var secondsSince1970 = BitConverter.ToInt32(b, i + linkerTimestampOffset);
            var dt = new DateTime(1970, 1, 1, 0, 0, 0);
            dt = dt.AddSeconds(secondsSince1970);
            dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours);
            return dt;
        }
开发者ID:Baggykiin,项目名称:BaggyBot-2,代码行数:25,代码来源:MiscTools.cs

示例15: IsFileLocked

		private static bool IsFileLocked( string path ) {
			FileStream stream = null;
			try {
				stream = new FileStream( path, FileMode.Open, FileAccess.Read );
			} catch {
				return true;
			} finally {
				stream?.Close();
			}

			return false;
		}
开发者ID:southernwind,项目名称:AradExtract,代码行数:12,代码来源:MainForm.cs


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