• anonymouse (unregistered)

    Mmmm, somehow, you'd think there'd be a better way...

  • Mike MacDonald (unregistered)

    blink blink

    Zoit!

  • (cs)

    Ooooooooooooooh - destructive boolean-test functions!

    Imagine the possibilities if instead of 4 characters of gibberish, it was a byte buffer of actual code?!!

  • Cyrus (unregistered)

    Narf? Oh man, my childhood memories are flooding back. What are we going to do tonight Brain?

    As a side story, simply opening the file and catching the error used to be faster than checking to see if it existed on old systems, don't know how that measures up now.

  • (cs)

    The FileExists function should be named RuinFileIfItExists. Then if used properly, it is useful. Hopefully you would get a permissions error or at least a write protection error for any critical files, but you could still do a lot of damage.

  • (cs)

    A 'catch' that does nothing but return false!

    I think I will start using that in all my code; now I have a reason to USE try/catch! </sarcasm>

  • (cs)

    I love that pice of code, so succint and self-documenting... its so neat I think I'll include it in every new program I ever write from now on.

  • Mikey Dub (unregistered)

    Of all the things I've read on this site, that definitely qualifies as the biggest cock up. Please tell me this was discovered in QA before going live.

  • Roy (unregistered)

    Actually this looks way to stupid to be in an actual running environemt. Looks more like a joke to me.

  • szukuro (unregistered)

    I propose File.Delete should be rewritten to throw an Exception if the file doesn't exist. Just imagine:

    public bool FileExists(path) { try { File.Delete(path); return true; } catch(FileNotFoundException){} return false; }

    Note: fot the function to return consistent results don't call it twice on existing files :D.

    CAPTCHA: onomatopoeia, now that's the real WTF

  • (cs) in reply to ParkinT
    ParkinT:
    A 'catch' that does nothing but return false!

    I think I will start using that in all my code; now I have a reason to USE try/catch! </sarcasm>

    On a side note, I don't mind catch blocks that do nothing, IF it's a very tiny narrowly constrained block of code, and there's a default value/action. For example, say you're reading some int from the environment:

       private final static int DEFAULT_VALUE_OF_X = 1024;
       int xEnvtVal = DEFAULT_VALUE_OF_X;
       try {
           xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
       } catch (Exception e) {
         // not set in envt or set-value is not an int: use default value
       }
    

    Of course, setting the default value in the exception might be more obvious, but I'm not (usually) that picky.

  • MooseBrains (unregistered)
    private bool FileExists(string strPath)
      {
          bool exists = false;
          try
          {
              File.WriteAllText(strPath, "narf");
              exists = true;
          }
          catch (Exception ex) {/* do nothing */}
          finally 
          {
              /* clean up */
              File.Delete(strPath);
          }
          return exists;
      }

    captcha: kungfu (Kii-aaah!)

  • dave (unregistered)

    Apart from the obvious destructiveness, the function doesn't even do what its name claims it does.

    The function is "test whether I can write to this file", which most programmers (i.e., everyone except those raised on MS-DOS) is a different question to whether it exists.

    Captcha: dreadlocks: alas, no. "receding hairline", actually.

  • Fredrik (unregistered)

    The really scary thing is that "if the file already exists, it is overwritten"..

    (http://msdn2.microsoft.com/en-us/library/system.io.file.writealltext.aspx)

    So if the file exists, the method will basically be saying 'yeah it DID exists....mwahah' :p

  • Sum-Yun-Gai (unregistered)

    ha this is hilarious.. "does this file exist?"

    "I don't know, let me try writing to it.."

    "Omg an exception was thrown - that means the file doesn't exist!" (hopefully)

  • (cs)

    I think this would make an interesting solution to storing information without storing them inside files:

    Create a directory (this is your variable), in which you create empty files. Just name them "0" or "1", 8 files at a time. That way you can store binary data directly in the FAT or the NTFS MFT. How nice is this! And you can perform some access control by controlling the NTFS ACL or just by locking files! The correct bit order must be controlled by creation date. That way you can only store one bit per second.

  • Hybor (unregistered)

    Seeing this, the first thing that comes to my mind is OUCH!

    captcha: vern - seeing through his eyes...

  • leeg (unregistered) in reply to szukuro
    szukuro:
    public bool FileExists(path) { try { File.Delete(path); return true; } catch(FileNotFoundException){} return false; }

    Or even:

    public bool FileExists(path) { try { File.Delete(path); } finally { return false; } }

    At least we guarantee accuracy and consistency ;-) [n.b. must be used by Administrator]

    Captcha: muhahaha....does this thing have a mindreading module?

  • Michael (unregistered) in reply to szukuro
    szukuro:
    I propose File.Delete should be rewritten to throw an Exception if the file doesn't exist. Just imagine:

    public bool FileExists(path) { try { File.Delete(path); return true; } catch(FileNotFoundException){} return false; }

    Note: fot the function to return consistent results don't call it twice on existing files :D.

    CAPTCHA: onomatopoeia, now that's the real WTF

    Shouldn't that function be named "FileUsedToExist"?

  • (cs) in reply to szukuro
    szukuro:
    I propose File.Delete should be rewritten to throw an Exception if the file doesn't exist. Just imagine:

    public bool FileExists(path) { try { File.Delete(path); return true; } catch(FileNotFoundException){} return false; }

    Note: fot the function to return consistent results don't call it twice on existing files :D.

    CAPTCHA: onomatopoeia, now that's the real WTF

    non-Idempotent functions FTW.

  • (cs) in reply to snoofle
    snoofle:
    On a side note, I don't mind catch blocks that do nothing, *IF* it's a very tiny narrowly constrained block of code, and there's a default value/action.
    Don't even bother catching the exception object, then...
    int xEnvtVal = DEFAULT_VALUE_OF_X;
    try {
        xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
    } catch { }

    That said, it's still evil.

    int xEnvtVal;
    if (!int.TryParse(System.getProperties().getProperty("X"), out xEnvtVal)) {
        xEnvtVal = DEFAULT_VALUE_OF_X;
    }
  • Andrew (unregistered) in reply to dave
    dave:
    Apart from the obvious destructiveness, the function doesn't even do what its name claims it does.

    The function is "test whether I can write to this file", which most programmers (i.e., everyone except those raised on MS-DOS) is a different question to whether it exists.

    Captcha: dreadlocks: alas, no. "receding hairline", actually.

    Even in MS-DOS there is a read-only bit. I don't think MS-DOS had a way to have a write-only file.

  • Tom (unregistered)

    "narf"... Does that translate to "Not A Real File"?

  • me (unregistered)

    I don't know why people are being so harsh. This is a well known, time proven algorithm. It was used extensively during the Salem witch trials.

    bool is_witch(victim) { witch = acquire_lock(victim); submerge(witch); sleep(3600); if (witch.is_dead()) return false; // not a witch; sorry return true; }

  • (cs)

    Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.

  • (cs) in reply to benryves
    benryves:
    snoofle:
    On a side note, I don't mind catch blocks that do nothing, *IF* it's a very tiny narrowly constrained block of code, and there's a default value/action.
    Don't even bother catching the exception object, then...
    int xEnvtVal = DEFAULT_VALUE_OF_X;
    try {
        xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
    } catch { }

    That said, it's still evil.

    int xEnvtVal;
    if (!int.TryParse(System.getProperties().getProperty("X"), out xEnvtVal)) {
        xEnvtVal = DEFAULT_VALUE_OF_X;
    }

    Hmmm, perhaps I should have stated I was writing Java code - not sure what language you responded with... syntax does vary a bit from language to langauge </smiles>

  • (cs) in reply to abx
    abx:
    Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.
    so the correct name of the function really should be:

    createTheFileIfItDoesntExistOrTrashItIfItDoes

    Nice!

  • foo (unregistered) in reply to abx
    Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.
    Ever heard of that little concept called permissions?
  • C Gomez (unregistered) in reply to Roy
    Roy:
    Actually this looks way to stupid to be in an actual running environemt. Looks more like a joke to me.

    It's not. Here's why.

    Many developers who are unfamiliar with Java or .NET have had to make the jump from VB or C++ because that's where their employer is taking them.

    Instead of taking the time to learn the new frameworks, and even explore them a little, they jump right in. And hey, we all have to get work done, so hmm, how can I get this done?

    This is what leads to this. For example, I saw littered throughout some code I was reviewing (C#) various ways to check if a string was empty instead of just comparing it to String.Empty. I saw another developer create all sorts of fancy state data to make sure some code was running on the UI thread instead of just testing InvokeRequired and then doing an Invoke to make sure it was.

    It's not a joke, its undereducation. There isn't an impetus from management to offer training, either. So really, if you're just punching the clock, you aren't out ahead of the curve reading about things so you're ready when you need them.

  • (cs) in reply to foo
    foo:
    Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.
    Ever heard of that little concept called permissions?
    Yes, but when WTF-developers create files with (in UNIX-ese) permissions 777, that doesn't really help.
  • (cs)

    I don't see the WTF, the code IS nicely indented!

  • (cs) in reply to foo
    foo:
    Umm, actually, the WriteAllText method actually creates the file if it does not exist, and overwrites it if it does. An exception will never be thrown.
    Ever heard of that little concept called permissions?
    Well if the .NET runtime doesn't have write permissions, then a SecurityException will be thrown when writing or creating, so the test would fail in both cases. Still doesn't make a very useful function, but granted, if there's something of some value on that file system, let us hope for their sake that the application doesn't have write permissions.
  • SomeCoder (unregistered)

    Oh dear god. Please tell me this code is a joke. Please? This is just.... gah...

    And that testing for a witch code was pretty damn good :)

  • Jens (unregistered)

    Would love to see the FileReader

    Example: /snip strContent = srReader.ReadToEnd().Replace( "narf", "" ); /snip

  • dustin (unregistered) in reply to anonymouse

    wow a wtf that could actually use the FileNotFound exception without trying to be funny

  • Yeah Right (unregistered)

    The person that wrote the original code is the kind of person that would leave a brick on the sidewalk under a pile of leaves.

    Merrily walking along, whimsically scuffing through the leaves - OW MY FOOT!

    Please schedule this person for immediate termination of some sort or another. Thank you.

  • (cs) in reply to snoofle
    snoofle:
    Hmmm, perhaps I should have stated I was writing Java code - not sure what language you responded with... syntax does vary a bit from language to langauge </smiles>
    I did think it looked a bit odd. I was going for C# as the OP is C#.

    Can you try and convert a value (in Java) without throwing an exception on bad input? Maybe it's just the way .NET likes to do things, but I've always found exceptions should only be used in, well, truly exceptional cases and if there is a way to avoid them (using int.TryParse instead of int.Parse) then do so.

  • Anonymous Bastard (unregistered)

    argh. someone should be beaten up severly over this.

  • So..... (unregistered) in reply to benryves
    benryves:
    snoofle:
    On a side note, I don't mind catch blocks that do nothing, *IF* it's a very tiny narrowly constrained block of code, and there's a default value/action.
    Don't even bother catching the exception object, then...
    int xEnvtVal = DEFAULT_VALUE_OF_X;
    try {
        xEnvtVal = Integer.parseInt(System.getProperties().getProperty("X"));
    } catch { }

    That said, it's still evil.

    int xEnvtVal;
    if (!int.TryParse(System.getProperties().getProperty("X"), out xEnvtVal)) {
        xEnvtVal = DEFAULT_VALUE_OF_X;
    }

    What do you think TryParse does....

  • (cs) in reply to So.....

    So the test destroys any existing data, eh? That's not a WTF, that just means the function is Heisenberg-compliant! As all atomic operations should be. (rim shot)

  • David Cameron (unregistered) in reply to Mikademus
    Mikademus:
    I don't see the WTF, the code IS nicely indented!

    That is only because VS.Net does that automatically.

  • Guido (unregistered)

    This is one of the happiest days in my TDWTF life...

    Aside from the "onomatopoeia captcha guy", nobody started his post with "The real WTF is that... ".

  • So..... (unregistered) in reply to Guido

    The real WTF is....

  • Bezalel (unregistered) in reply to Guido
    Guido:
    Aside from the "onomatopoeia captcha guy", nobody started his post with "The real WTF is that... ".

    I guess I'll have to do it.

    The real WTF is that the function doesn't return FILE_NOT_FOUND if it doesn't exist.

  • Anonymous (unregistered) in reply to C Gomez
    C Gomez:
    For example, I saw littered throughout some code I was reviewing (C#) various ways to check if a string was empty instead of just comparing it to String.Empty.

    OK, I have to pull you up on this. Officially, the best way is to check that the string's length is zero, as that is faster than comparing to String.Empty.

    Otherwise you've got a valid point, though.

  • Poppa Vein (unregistered)

    .NET System.IO.File.Exists (MS.NET 1.1) is a WTF anyway... From MSDN:

    "Returns true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path."

    That is, "the file may exist, but we're not going to tell ya".

  • (cs)

    Actually, if the function was renamed "FileCanBeTrashedAndTruncatedAndWrittenTo", it would be pretty good code.

    Quite often calling a FileExists() function is the wrong thing. Just knowing a file exists isnt what you want to do-- you actually want to know if the file is readable or writeable by you. Just about the only way to make sure is to try reading or writing. No, stat() just tells you what the file flags WERE a little bit in the past, not very useful right now or a nanosecond later.

  • (cs) in reply to MooseBrains
    MooseBrains:
    private bool FileExists(string strPath)
      {
          bool exists = false;
          try
          {
              File.WriteAllText(strPath, "narf");
              exists = true;
          }
          catch (Exception ex) {/* do nothing */}
          finally 
          {
              /* clean up */
              File.Delete(strPath);
          }
          return exists;
      }

    captcha: kungfu (Kii-aaah!)

    Here's a simpler version:

    private bool FileExists(string strPath)
      {
          try{
                File.Delete(strPath);
          }
          catch (Exception ex) {/* do nothing */}
          return false;
      }
  • Sven (unregistered) in reply to Anonymous
    Anonymous:
    C Gomez:
    For example, I saw littered throughout some code I was reviewing (C#) various ways to check if a string was empty instead of just comparing it to String.Empty.

    OK, I have to pull you up on this. Officially, the best way is to check that the string's length is zero, as that is faster than comparing to String.Empty.

    Otherwise you've got a valid point, though.

    .Net 2.0 also offers the String.IsNullOrEmpty static method, which is equivalent to doing (str != null && str.Length > 0).

    And in VB.NET the compiler is smart enough to automatically replace comparisons to an empty string with something that's equivalent to that.

  • Sven (unregistered) in reply to Sven
    Sven:
    .Net 2.0 also offers the String.IsNullOrEmpty static method, which is equivalent to doing (str != null && str.Length > 0).
    Obviously I meant it's equivalent to (str == null || str.Length == 0).

    Let's not randomly negate expression, shall we. :)

Leave a comment on “Fun with Files”

Log In or post as a guest

Replying to comment #:

« Return to Article