Skip to content

Commit

Permalink
Refactor ToFile
Browse files Browse the repository at this point in the history
  • Loading branch information
engineering87 committed Oct 6, 2024
1 parent bf29712 commit cf9197a
Showing 1 changed file with 27 additions and 45 deletions.
72 changes: 27 additions & 45 deletions SharpHelpers/SharpHelpers/StreamHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,58 +121,40 @@ public static Stream FromArray(this byte[] arrayToConvert)
/// <returns></returns>
public static bool ToFile(this Stream stream, string fileName)
{
return ToFile(stream, fileName, true, Encoding.Default);
}

return ToFile(stream, fileName, true);
}

/// <summary>
/// Writes a stream to file
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="overrideExisting">If set to <c>true</c> override existing file.</param>
/// <returns>True if successful</returns>
public static bool ToFile(this Stream stream, string fileName, bool overrideExisting)
{
return ToFile(stream, fileName, overrideExisting, Encoding.Default);
}

/// <summary>
/// Writes a stream to file
/// </summary>
/// <param name="stream"></param>
/// <param name="fileName"></param>
/// <param name="overrideExisting"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static bool ToFile(this Stream stream, string fileName, bool overrideExisting, Encoding encoding)
{
//Check if the sepcified file exists
if (File.Exists(fileName))
if (overrideExisting)
File.Delete(fileName);
else
throw new AccessViolationException("File already exists");

try
{
//Create the file if it does not exist and open it
stream.Position = 0;
using (var fileStream = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite))
{
var reader = new BinaryReader(stream);
var writer = new BinaryWriter(fileStream, encoding);
writer.Write(reader.ReadBytes((int)stream.Length));
writer.Flush();
writer.Close();
reader.Close();
fileStream.Close();
return true;
}
}
catch
{
return false;
}
public static bool ToFile(this Stream stream, string fileName, bool overrideExisting)
{
try
{
if (File.Exists(fileName))
{
if (overrideExisting)
File.Delete(fileName);
else
throw new IOException("File already exists");
}

stream.Position = 0;
using (var fileStream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write))
{
stream.CopyTo(fileStream);
}

return true;
}
catch (IOException)
{
return false;
}
}

/// <summary>
Expand Down

0 comments on commit cf9197a

Please sign in to comment.