Results 1 to 6 of 6

Thread: [RESOLVED] Code simplification

  1. #1

    Thread Starter
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Resolved [RESOLVED] Code simplification

    Hi,

    I have the following code:
    Code:
    if (!File.Exists(path))
    {
    	FileStream newFile = File.Create(path);
    	newFile.Dispose();
    }
    Will the following work exactly the same?
    Code:
    if (!File.Exists(path))
    {
    	File.Create(path).Dispose();
    }
    Thanks
    Delete it. They just clutter threads anyway.

  2. #2
    Member
    Join Date
    Dec 2005
    Location
    Philadelphia
    Posts
    48

    Re: Code simplification

    It is the same.

    going to assume you're trying to delete the file though. If that is the case just use File.Delete(path).

  3. #3

    Thread Starter
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: Code simplification

    No, I'm creating an empty file.
    First I used just File.Create(path), and I didn't realize that it returns the filestream created and leaves it open.
    So to close the file I figured I'd use Dispose(), but I might be totally mistaken with the usage.
    Delete it. They just clutter threads anyway.

  4. #4

  5. #5

    Thread Starter
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: Code simplification

    Well you actually have an excellent point there

    This is an old piece of code I had lying around that uses the StreamWriter directly (as in 'new StreamWriter(path)'), which requires the file to exist.
    At that time I probably didn't realize that I could use a FileStream object first and do that...
    Delete it. They just clutter threads anyway.

  6. #6

    Thread Starter
    Frenzied Member TheBigB's Avatar
    Join Date
    Mar 2006
    Location
    *Stack Trace*
    Posts
    1,511

    Re: Code simplification

    And that isn't even true...
    The StreamWriter doesn't throw FileNotFound exceptions.
    I'm clueless why I actually did that check... Well, better to be safe than sorry.

    But I guess I can Dispose that code fragment altogether now.
    Delete it. They just clutter threads anyway.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width