Skip to content

Instantly share code, notes, and snippets.

@Buildstarted
Created January 15, 2013 05:56
Show Gist options
  • Select an option

  • Save Buildstarted/4536542 to your computer and use it in GitHub Desktop.

Select an option

Save Buildstarted/4536542 to your computer and use it in GitHub Desktop.
namespace ConsoleApplication403
{
using System;
using System.ComponentModel;
using System.IO;
class Program
{
static void Main()
{
FileIO.OpenOrCreate("e:\\test.txt", (s, f) =>
{
switch (f)
{
case FileOpenType.Created:
//file was created
Console.WriteLine("Created");
break;
case FileOpenType.Opened:
//preexisting file
Console.WriteLine("Opened");
break;
}
s.Write(System.Text.ASCIIEncoding.ASCII.GetBytes("HELLO!"), 0, 6);
s.Close();
});
Console.ReadKey();
}
}
public static class FileIO
{
public static FileStream OpenOrCreate(string filename, Action<FileStream, FileOpenType> callback)
{
var stream = new FileStream(filename, FileMode.OpenOrCreate);
Win32Exception ex = new Win32Exception();
switch (ex.NativeErrorCode)
{
case 183:
callback(stream, FileOpenType.Opened);
break;
default:
callback(stream, FileOpenType.Created);
break;
}
return stream;
}
}
public enum FileOpenType
{
Opened,
Created
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment