FileStream Save() Extension - Easily Save Your FileStreams with the Option of No-Overwrite

an extension to allow fast simple saving without worrying about overwriting a file

With these extensions, you can save a FileStream as simple as this:

Now if you run it again, it will save another file named file[1].txt, then file[2].txt and so on. If you want to overwrite a file, simply state true for the overwrite flag:
fs.Save(@"C;/file.txt", true);

Here is the code:
public static string Save(this FileStream file, 
  string path)
{ return file.Save(path, false); }
public static string Save(this FileStream file, 
  string path, bool overwrite)
  int count = 1;
  string folder = Path.GetDirectoryName(path);
  if (!Directory.Exists(folder)) 
  int fileSize = Convert.ToInt32(file.Length);
  string fileName = Path.GetFileName(file.Name);
  Byte[] bytes = new Byte[fileSize];
  file.Read(bytes, 0, fileSize);
  string root = Path.GetDirectoryName(path) + 
    "\\" + Path.GetFileNameWithoutExtension(path);
  while (!overwrite && File.Exists(path))
    path = root + "[" + count++.ToString() + 
      "]" + Path.GetExtension(path);
  File.WriteAllBytes(path, bytes);
  return Path.GetFileName(path);
Comments are closed