本文整理汇总了C#中System.IO.FileStream.?.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# FileStream.?.Dispose方法的具体用法?C# FileStream.?.Dispose怎么用?C# FileStream.?.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileStream
的用法示例。
在下文中一共展示了FileStream.?.Dispose方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LoadAsync
public async Task<IEnumerable<StreamBase>> LoadAsync()
{
List<StreamBase> streams = new List<StreamBase>();
FileStream fsAsync = null;
try
{
fsAsync = new FileStream(FilePath,
FileMode.Open,
FileAccess.Read,
FileShare.None,
4096,
true);
using (StreamReader sr = new StreamReader(fsAsync))
{
fsAsync = null;
string line = string.Empty;
while ((line = await sr.ReadLineAsync().ConfigureAwait(false)) != null)
{
StreamBase sb = ParseIntoStream(line);
if (sb != null)
{
streams.Add(sb);
}
}
}
}
catch (FileNotFoundException e)
{
Utils.LogException(e);
}
finally
{
fsAsync?.Dispose();
}
return streams;
}
示例2: Write
public static void Write(string value, bool writeToFile = false, Exception exception = null)
{
FileStream fileStream = null;
try
{
fileStream = new FileStream(LogFileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
using (var streamWriter = new StreamWriter(fileStream, Encoding.UTF8))
{
fileStream = null;
if (exception != null)
{
Debug.WriteLine($"[{DateTime.Now}]: {value} [Exception: {exception}]");
if (writeToFile)
streamWriter.WriteLine($"[{DateTime.Now}]: {value} [Exception: {exception}]");
}
else
{
Debug.WriteLine($"[{DateTime.Now}]: {value}");
if (writeToFile)
streamWriter.WriteLine($"[{DateTime.Now}]: {value}");
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Logger error: {ex}");
}
finally
{
fileStream?.Dispose();
}
}
示例3: WriteTextToFileAsync
private static async Task WriteTextToFileAsync(string text, int rounds = 1)
{
if (text == null) { throw new ArgumentNullException(nameof(text)); }
if (rounds < 1) { throw new ArgumentException("WriteTextToFileAsync: rounds cannot be < 1"); }
bool tryAgain = false;
FileStream fsAsync = null;
try
{
fsAsync = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.None, 1024, true);
using (StreamWriter sw = new StreamWriter(fsAsync))
{
fsAsync = null;
await sw.WriteLineAsync(text).ConfigureAwait(false);
}
}
catch (IOException)
{
tryAgain = (rounds > 1);
}
finally
{
fsAsync?.Dispose();
}
if (tryAgain)
{
int variation = DateTime.UtcNow.Millisecond;
/*
* we want the delay to increase as the number of attempts left decreases
* as rounds increases, (1 / rounds) decreases
* => as (1 / rounds) decreases, (25 / (1 / rounds)) increases
*
* we convert rounds to decimal because otherwise it would do integer division
* e.g. 1 / 3 = 0
*/
decimal fixedWait = 25 / (1 / Convert.ToDecimal(rounds));
int toWait = Convert.ToInt32(fixedWait) + variation;
await Task.Delay(toWait).ConfigureAwait(false);
await WriteTextToFileAsync(text, rounds - 1).ConfigureAwait(false);
}
}
示例4: SaveToFile
public override void SaveToFile(string fileName, Encoding enc)
{
//
var newLinePos = new List<int>(Count);
//create temp file
var dir = Path.GetDirectoryName(fileName);
if (dir != null) {
var tempFileName = Path.Combine(dir, Path.GetFileNameWithoutExtension(fileName) + ".tmp");
FileStream tempFs = null;
StreamReader sr = new StreamReader(fs, fileEncoding);
try {
tempFs = new FileStream(tempFileName, FileMode.Create);
using (StreamWriter sw = new StreamWriter(tempFs, enc)) {
int fsLen = (int)tempFs.Length;
tempFs = null;
sw.Flush();
for (int i = 0; i < Count; i++) {
newLinePos.Add(fsLen);
var sourceLine = ReadLine(sr, i);//read line from source file
bool lineIsChanged = lines[i] != null && lines[i].IsChanged;
var line = lineIsChanged ? lines[i].Text : sourceLine;
//call event handler
if (LinePushed != null) {
var args = new LinePushedEventArgs(sourceLine, i, lineIsChanged ? line : null);
LinePushed(this, args);
if (args.SavedText != null)
line = args.SavedText;
}
//save line to file
sw.Write(line);
if (i < Count - 1)
sw.Write(SaveEOL);
sw.Flush();
}
}
} finally {
tempFs?.Dispose();
}
//clear lines buffer
for (int i = 0; i < Count; i++)
lines[i] = null;
//deattach from source file
sr.Dispose();
fs.Dispose();
//delete target file
if (File.Exists(fileName))
File.Delete(fileName);
//rename temp file
File.Move(tempFileName, fileName);
}
//binding to new file
sourceFileLinePositions = newLinePos;
fs = new FileStream(fileName, FileMode.Open);
fileEncoding = enc;
}
示例5: Execute_LoadPlayerDataFromFile
//.........这里部分代码省略.........
Uuid = user.Uuid
});
}
userCacheCollection.Clear();
}
break;
}
case "ops.json":
{
var opsCollection = JsonConvert.DeserializeObject<List<Op>>(json);
if (opsCollection != null)
{
// Remove existing true values
foreach (var source in GlobalPlayersCollection.Where(x => x.IsOperator))
{
source.IsOperator = false;
source.OpLevel = null;
}
foreach (var globalPlayer in GlobalPlayersCollection)
{
foreach (var op in opsCollection.Where(x => globalPlayer.Uuid.Equals(x.Uuid)))
{
globalPlayer.IsOperator = true;
globalPlayer.OpLevel = op.Level;
}
}
opsCollection.Clear();
}
break;
}
case "banned-players.json":
{
var bannedPlayersCollection = JsonConvert.DeserializeObject<List<BannedPlayer>>(json);
if (bannedPlayersCollection != null)
{
// Remove existing true values
foreach (var source in GlobalPlayersCollection.Where(x => x.IsBanned))
{
source.IsBanned = false;
source.BanExpires = null;
source.BanReason = null;
source.BanSource = null;
}
foreach (var globalPlayer in GlobalPlayersCollection)
{
foreach (
var bannedPlayer in
bannedPlayersCollection.Where(x => globalPlayer.Uuid.Equals(x.Uuid)))
{
globalPlayer.IsBanned = true;
globalPlayer.BanReason = bannedPlayer.Reason;
globalPlayer.BanSource = bannedPlayer.Source;
globalPlayer.BanExpires = bannedPlayer.Expires;
}
}
bannedPlayersCollection.Clear();
}
break;
}
case "whitelist.json":
{
var whitelistedCollection = JsonConvert.DeserializeObject<List<Whitelist>>(json);
if (whitelistedCollection != null)
{
// Remove existing true values
foreach (var source in GlobalPlayersCollection.Where(x => x.IsWhitelisted))
source.IsWhitelisted = false;
foreach (var globalPlayer in from globalPlayer in GlobalPlayersCollection
from whitelist in whitelistedCollection.Where(x => globalPlayer.Uuid.Equals(x.Uuid))
select globalPlayer)
globalPlayer.IsWhitelisted = true;
whitelistedCollection.Clear();
}
break;
}
}
}
}
finally
{
stream?.Dispose();
}
}
示例6: DisposableNotDisposed
public DisposableNotDisposed(FileStream fs)
{
var fs1 = new FileStream(@"c:\foo.txt", FileMode.Open); // Noncompliant - directly instantiated with new
var fs2 = File.Open(@"c:\foo.txt", FileMode.Open); // Noncompliant - instantiated with factory method
Stream fs3 = new FileStream(@"c:\foo.txt", FileMode.Open); // Noncompliant - declaration type should not matter
var s = new WebClient(); // Noncompliant - another tracked type
var fs4 = new FileStream(@"c:\foo.txt", FileMode.Open); // Compliant - passed to a method
NoOperation(fs4);
FileStream fs5; // Compliant - used properly
using (fs5 = new FileStream(@"c:\foo.txt", FileMode.Open))
{
// do nothing but dispose
}
using (var fs6 = new FileStream(@"c:\foo.txt", FileMode.Open)) // Compliant - used properly
{
// do nothing but dispose
}
var fs7 = new FileStream(@"c:\foo.txt", FileMode.Open); // Compliant - Dispose()
fs7.Dispose();
var fs8 = new FileStream(@"c:\foo.txt", FileMode.Open); // Compliant - Close()
fs8.Close();
var fs9 = new FileStream(@"c:\foo.txt", FileMode.Open); // Compliant - disposed using elvis operator
fs9?.Dispose();
FileStream fs10 = fs; // Compliant - not instantiated directly
var fs11 = new FileStream(@"c:\foo.txt", FileMode.Open); // Compliant - aliased
var newFs = fs11;
var fs12 = new BufferedStream(fs); // Compliant - constructed from another stream
var fs13 = new StreamReader(fs); // Compliant - constructed from another stream
var fs14 = new FileStream(@"c:\foo.txt", FileMode.Open); // Compliant - passed to another method (or constructor)
var fs15 = new BufferedStream(fs14); // Compliant - not tracked
var fs16 = new FileStream(@"c:\foo.txt", FileMode.Open); // Compliant - aliased
var myAnonymousType = new { SomeField = fs16 };
FileStream fs17; // Compliant - no initializer, should not fail
FileStream
fs18 = new FileStream(@"c:\foo.txt", FileMode.Open), // Noncompliant - test issue location
fs19; // Compliant - not instantiated
FileStream fs20 = new FileStream(@"c:\foo.txt", FileMode.Open); // Compliant - aliased
Stream fs21;
fs21 = fs20;
FileStream fs22;
fs22 = new FileStream(@"c:\foo.txt", FileMode.Open); // Noncompliant
field_fs4.Dispose();
field_fs5 = new FileStream(@"c:\foo.txt", FileMode.Open); // Noncompliant
NoOperation(field_fs6);
field_fs6 = new FileStream(@"c:\foo.txt", FileMode.Open); // Compliant - field_fs6 gets passed to a method
field_fs7 = new FileStream(@"c:\foo.txt", FileMode.Open); // Noncompliant - even if field_fs7's type is object
NoOperation(this.field_fs8);
}
示例7: Step5
/// <summary>
/// Step #5
///
/// Save the unpacked file.
/// </summary>
/// <returns></returns>
private bool Step5()
{
FileStream fStream = null;
byte[] overlayData = null;
try
{
// Determine if the file has any overlay data..
var lastSection = this.File.Sections.Last();
var fileSize = lastSection.SizeOfRawData + lastSection.PointerToRawData;
if (fileSize < this.File.FileData.Length)
{
// Overlay exists, copy it..
overlayData = new byte[this.File.FileData.Length - fileSize];
Array.Copy(this.File.FileData, fileSize, overlayData, 0, this.File.FileData.Length - fileSize);
}
}
catch
{
return false;
}
try
{
// Open the unpacked file for writing..
var unpackedPath = this.File.FilePath + ".unpacked.exe";
fStream = new FileStream(unpackedPath, FileMode.Create, FileAccess.ReadWrite);
// Write the dos header back to the file..
fStream.WriteBytes(Helpers.GetStructureBytes(this.File.DosHeader));
// Write the dos stub back to the file if it exists..
if (this.File.DosStubSize > 0)
fStream.WriteBytes(this.File.DosStubData);
// Determine if we should remove the .bind section..
if (!Program.HasArgument("--keepbind"))
{
// Remove the .bind section from the file..
this.File.Sections.Remove(this.File.GetSection(".bind"));
}
// Rebuild the NT headers of the file..
var ntHeaders = this.File.NtHeaders;
var lastSection = this.File.Sections[this.File.Sections.Count - 1];
if (!Program.HasArgument("--keepbind"))
ntHeaders.FileHeader.NumberOfSections--;
ntHeaders.OptionalHeader.AddressOfEntryPoint = this.StubHeader.OriginalEntryPoint;
ntHeaders.OptionalHeader.SizeOfImage = lastSection.VirtualAddress + lastSection.VirtualSize;
// Write the Nt headers to the file..
fStream.WriteBytes(Helpers.GetStructureBytes(ntHeaders));
// Write the sections to the file..
foreach (var s in this.File.Sections)
{
// Obtain the sections data from the original file..
var sectionData = new byte[s.SizeOfRawData];
Array.Copy(this.File.FileData, this.File.GetFileOffsetFromRva(s.VirtualAddress), sectionData, 0, s.SizeOfRawData);
// Write the section header to the file..
fStream.WriteBytes(Helpers.GetStructureBytes(s));
// Write the section data to the file..
var sectionOffset = fStream.Position;
fStream.Position = s.PointerToRawData;
// Determine if this is the code section..
if (s.SizeOfRawData == this.CodeSection.SizeOfRawData && s.PointerToRawData == this.CodeSection.PointerToRawData)
fStream.WriteBytes(this.CodeSectionData ?? sectionData);
else
fStream.WriteBytes(sectionData);
// Reset the file offset..
fStream.Position = sectionOffset;
}
// Skip to the end of the stream..
fStream.Position = fStream.Length;
// Write the overlay back to the file if it exists..
if (overlayData != null)
fStream.WriteBytes(overlayData);
return true;
}
catch
{
return false;
}
finally
{
fStream?.Dispose();
//.........这里部分代码省略.........
示例8: LoadOPLFile
private bool LoadOPLFile(string fileName, uint startTime, uint endTime)
{
FileStream fs = null;
_signalElements = new SignalElements();
string lastDataEntryTime = "";
List<string> currentDataStrings = null;
_currentPhase = Phase.HeaderVersion;
bool parseError = false;
List<Task> parseTasks = null;
try {
fs = new FileStream(fileName, FileMode.Open);
using (TextReader reader = new StreamReader(fs)) {
fs = null;
_header = new OPLHeader();
string line;
while ((line = reader.ReadLine()) != null) {
switch (_currentPhase) {
case Phase.HeaderVersion:
if (!_header.ParseHeaderVersion(line)) {
Console.WriteLine("Unsupported file version detected");
return false;
}
Console.WriteLine("File version {0} detected", Header.Version);
_currentPhase = Phase.Header1;
break;
case Phase.Header1:
if (!_header.ParseHeader1(line)) {
Console.WriteLine("Cannot parse header");
return false;
}
_currentPhase = Phase.Header2;
break;
case Phase.Header2:
if (!_header.ParseHeader2(line)) {
Console.WriteLine("Cannot parse header");
return false;
}
Console.WriteLine("Header successfully parsed");
_currentPhase = Phase.SignalElements;
break;
case Phase.SignalElements:
SignalElement element = new SignalElement();
if (element.ParseData(line)) {
element.Freeze();
_signalElements.Add(element);
if ((uint)_signalElements.Count == _header.SignalElementCount) {
// All elements found, prepare next phase.
Console.WriteLine("Signal element data successfully parsed");
_currentPhase = Phase.Data;
_dataEntries = new ConcurrentDictionary<uint, SignalDataEntry>(Environment.ProcessorCount,
(int)(_header.EndTimeAsUnixTime - _header.StartTimeAsUnixTime + 2));
parseTasks = new List<Task>((int)(_header.EndTimeAsUnixTime - _header.StartTimeAsUnixTime + 2));
// A data entry contains a header as well, therefore SignalElementCount + 1.
currentDataStrings = new List<string>((int)_header.SignalElementCount + 1);
}
break;
}
Console.WriteLine("Couldn't parse signal element data");
return false;
case Phase.Data:
if (parseError) {
return false;
}
if (lastDataEntryTime != _header.EndTimeAsUnixTime.ToString()) {
if (currentDataStrings.Count < _header.SignalElementCount + 1) {
currentDataStrings.Add(line);
}
if (currentDataStrings.Count == _header.SignalElementCount + 1) {
var parseStrings = new List<string>(currentDataStrings);
parseTasks.Add(Task.Factory.StartNew(
() => ParseDataEntry(parseStrings, ref parseError)));
lastDataEntryTime = Utils.GetNumericValue(line, 0);
currentDataStrings = new List<string>((int)_header.SignalElementCount + 1);
}
}
break;
}
}
}
}
finally {
fs?.Dispose();
}
Task.WaitAll(parseTasks.ToArray());
if (!parseError && _dataEntries.Count == _header.EndTimeAsUnixTime - _header.StartTimeAsUnixTime + 2) {
Console.WriteLine("All signal element states successfully parsed");
if (startTime != 0 || endTime != uint.MaxValue) {
_dataEntries = new ConcurrentDictionary<uint, SignalDataEntry>(
_dataEntries.Where(de => de.Key >= startTime && de.Key <= endTime));
_header.SetFilteredTimeRange(startTime, endTime);
Console.WriteLine($"Data filtered. Start: {Utils.UnixTimeToDateTime(startTime).ToString()} " +
$"End: {Utils.UnixTimeToDateTime(endTime).ToString()}");
}
_header.Freeze();
//.........这里部分代码省略.........
示例9: ParseConfigurationFile
private bool ParseConfigurationFile(string fileName)
{
_strikeInType = SignalElement.Type.None;
_strikeOutType = SignalElement.Type.None;
_strikeIn = new List<string>();
_strikeOut = new List<string>();
_blockedSignals = new List<string>();
_maxVehicles = 0;
_timeOut = 0;
string line;
FileStream fs = null;
Phase currentPhase = Phase.none;
try {
fs = new FileStream(fileName, FileMode.Open);
using (TextReader reader = new StreamReader(fs)) {
fs = null;
while ((line = reader.ReadLine()) != null) {
if (String.IsNullOrWhiteSpace(line) || line.StartsWith(";")) {
continue;
}
switch (line) {
case "[Strike-in]":
currentPhase = Phase.StrikeIn;
continue;
case "[Strike-out]":
currentPhase = Phase.StrikeOut;
continue;
case "[Signals]":
currentPhase = Phase.Signals;
continue;
case "[MaxVehicles]":
currentPhase = Phase.MaxVehicles;
continue;
case "[Timeout]":
currentPhase = Phase.TimeOut;
continue;
default:
if (line.StartsWith("[") && line.EndsWith("]")) {
currentPhase = Phase.none;
continue;
}
break;
}
switch (currentPhase) {
case Phase.StrikeIn:
if (_strikeInType == SignalElement.Type.None) {
uint elementTypeParsedValue = Convert.ToUInt32(line);
if (elementTypeParsedValue != 0 &&
!Enum.IsDefined(typeof(SignalElement.Type), elementTypeParsedValue)) {
return false;
}
_strikeInType = (SignalElement.Type)elementTypeParsedValue;
break;
}
_strikeIn.Add(line);
break;
case Phase.StrikeOut:
if (_strikeOutType == SignalElement.Type.None) {
uint elementTypeParsedValue = Convert.ToUInt32(line);
if (elementTypeParsedValue != 0 &&
!Enum.IsDefined(typeof(SignalElement.Type), elementTypeParsedValue)) {
return false;
}
_strikeOutType = (SignalElement.Type)elementTypeParsedValue;
break;
}
_strikeOut.Add(line);
break;
case Phase.Signals:
_blockedSignals.Add(line);
break;
case Phase.MaxVehicles:
_maxVehicles = Convert.ToInt32(line);
break;
case Phase.TimeOut:
_timeOut = Convert.ToInt32(line);
break;
}
}
}
}
finally {
fs?.Dispose();
}
return _strikeInType != SignalElement.Type.None && _strikeIn.Count > 0 &&
_strikeOutType != SignalElement.Type.None && _strikeOut.Count > 0 &&
_blockedSignals.Count > 0 && _maxVehicles > 0 && _timeOut > 0;
}
示例10: ParseIntergreenConfig
private bool ParseIntergreenConfig(string fileName)
{
string line;
FileStream fs = null;
bool success = false;
string name = null;
Dictionary<string, int> newEntries = null;
string currentSignalGroup = null;
try {
fs = new FileStream(fileName, FileMode.Open);
using (TextReader reader = new StreamReader(fs)) {
fs = null;
while ((line = reader.ReadLine()) != null) {
if (String.IsNullOrWhiteSpace(line) || line.StartsWith(";")) {
continue;
}
if (line.StartsWith("[") && line.EndsWith("]")) {
if (newEntries != null) {
// New section starts, add the previously parsed values if they exist
_intergreenTimes.Add(currentSignalGroup, newEntries);
}
newEntries = new Dictionary<string, int>();
currentSignalGroup = line.Trim(new char[] {'[', ']'});
continue;
}
if (name == null) {
name = line;
} else {
int seconds;
if (!Int32.TryParse(line, out seconds)) {
return false;
}
newEntries.Add(name, seconds);
success = true;
name = null;
}
}
if (newEntries != null) {
// End of file, add the previously parsed values if they exist
_intergreenTimes.Add(currentSignalGroup, newEntries);
}
}
}
finally {
fs?.Dispose();
}
return success;
}