Created
January 15, 2013 05:56
-
-
Save Buildstarted/4536542 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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