• (cs)

    I do tend to like utility methods like WriteToFile that include a boolean parameter for creating the file if it doesn't exist.

  • (cs) in reply to Talib
    Talib:
    Well surprisingly this seems to be the correct way for checking if a file is in use according to: http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use
    Wow! Finally, we have discovered where these "princely"-priced enterprise-y solutions come from!
    Talib:
    The problem was that the anti-virus seemed to be quicker sometimes and lock the file for access.
    More likely it was Windows Media Player.
  • (cs) in reply to Mike
    Mike:
    Kids are TRWTF, AJ. I mean, what useful purpose do they serve, other than to make a mess of the place you had to move to because his bachelor pad wasn't "homey" enough, destroy all the expensive crap you made him buy you, and leave the lights and TV on until they're old enough to finance a major drug addiction?
    They are literally the most annoying thing that you'll ever find, and they are going to make your life hell for many years. Unfortunately humans are programmed to want them anyways...
  • (cs) in reply to spamcourt
    spamcourt:
    Mike:
    Kids are TRWTF, AJ. I mean, what useful purpose do they serve, other than to make a mess of the place you had to move to because his bachelor pad wasn't "homey" enough, destroy all the expensive crap you made him buy you, and leave the lights and TV on until they're old enough to finance a major drug addiction?
    They are literally the most annoying thing that you'll ever find, and they are going to make your life hell for many years. Unfortunately humans are programmed to want them anyways...
    You are doing it wrong. It's not about "wanting" them, Its about competition. Your neighbors are going to have these things, your friends are, so you should get a few too. That way you can, raise them, teach them, and pit them against each other in all sorts of various sports activities. Some have better skills in other areas, so you pit them against each other in activities of the mind. Ya so what if they are expensive, and have a tendency to develop major drug addictions, If you can get one that makes a lot of money, then quite frankly, you win!
  • (cs)

    Why, if C# looks exactly as Java, do method names start with upper-case? Is this some MS way of trying to be "special"? This is just retarded.

  • (cs) in reply to ubersoldat
    ubersoldat:
    Why, if C# looks exactly as Java, do method names start with upper-case? Is this some MS way of trying to be "special"? This is just retarded.

    C# is proper, Java is not.

  • Maciej (unregistered) in reply to PiisAWheeL
    PiisAWheeL:
    spamcourt:
    Mike:
    Kids are TRWTF, AJ. I mean, what useful purpose do they serve, other than to make a mess of the place you had to move to because his bachelor pad wasn't "homey" enough, destroy all the expensive crap you made him buy you, and leave the lights and TV on until they're old enough to finance a major drug addiction?
    They are literally the most annoying thing that you'll ever find, and they are going to make your life hell for many years. Unfortunately humans are programmed to want them anyways...
    You are doing it wrong. It's not about "wanting" them, Its about competition. Your neighbors are going to have these things, your friends are, so you should get a few too. That way you can, raise them, teach them, and pit them against each other in all sorts of various sports activities. Some have better skills in other areas, so you pit them against each other in activities of the mind. Ya so what if they are expensive, and have a tendency to develop major drug addictions, If you can get one that makes a lot of money, then quite frankly, you win!

    Back in my days, we called these Pokemon.

  • Jordan Rieger (unregistered)

    TRWTF is that the WriteToFile() method is void -- so even if IsFileLocked() returns true, the caller has no way of knowing if what he wanted to write actually got written! A void method should always do what its name says it will do, or throw an exception on failure. Correcting this ironically leads to a funny bit of refactoring, since to throw an exception on a write failure would simply involve removing the IsFileLocked() call completely and allowing any exception to bubble up to the caller :-)

  • (cs)

    I think I did this, and even used the same source, when creating a small c# utility to copy a picture to a bunch of cheap android tablets I use as digital picture frames.

    The process was I copy a picture to a certain directory, it's resized and uploaded using an FTP server on the tablets. I used a FilesystemWatcher on this directory, but it had the issue where it would be triggered right away when a picture was copied, even though the copy operation wasn't done. Try a file lock, if fails, try again in 2 seconds, if fails try again in 4 seconds, up to 10 tries.

  • Z (unregistered) in reply to spamcourt
    spamcourt:
    Mike:
    Kids are TRWTF, AJ. I mean, what useful purpose do they serve, other than to make a mess of the place you had to move to because his bachelor pad wasn't "homey" enough, destroy all the expensive crap you made him buy you, and leave the lights and TV on until they're old enough to finance a major drug addiction?
    They are literally the most annoying thing that you'll ever find, and they are going to make your life hell for many years. Unfortunately humans are programmed to want them anyways...

    No, chatboard trolls are the most annoying thing you'll ever find. Although you can make a pretty convincing argument that trolls are not really a lifeform, and they can always be safely ignored, you still have to step over the stinking mess they leave on the carpet. No, wait; that was cats.

  • Ter (unregistered) in reply to Talib
    Talib:
    Well surprisingly this seems to be the correct way for checking if a file is in use according to: http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use

    I had a similar issue where I wrote a program for a closed system: When a technician plugged in a USB drive (only they had access to the USB ports) the system automatically checked the drive for an update file. The problem was that the anti-virus seemed to be quicker sometimes and lock the file for access. Thus I needed a way to check when the file became available. I used the method above.

    I must say I used a loop in conjunction with a fail timer (if the file did not become available after a few seconds).

    Well....if stackoverflow says that's the way to do it....

  • Mikey (unregistered) in reply to Ter
    Ter:
    Talib:
    Well surprisingly this seems to be the correct way for checking if a file is in use according to: http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use

    I had a similar issue where I wrote a program for a closed system: When a technician plugged in a USB drive (only they had access to the USB ports) the system automatically checked the drive for an update file. The problem was that the anti-virus seemed to be quicker sometimes and lock the file for access. Thus I needed a way to check when the file became available. I used the method above.

    I must say I used a loop in conjunction with a fail timer (if the file did not become available after a few seconds).

    Well....if stackoverflow says that's the way to do it....
    OTOH, what's wrong with that?

    Suppose most of the time everything works, but occasionally the file ain't there (as described in the stackoverflow link). That would be an exceptional situation - so I don't have too much problem with testing that way....

    Then again, I;m a C programmer so this concept of Exceptions is still a bit too new for me ;)

  • (cs)

    Or you could try to handle specific exceptions.

    http://msdn.microsoft.com/en-us/library/system.io.filenotfoundexception.aspx

    try {
       // code
    } catch (System.IO.FileNotFoundException fnfe) {
       // do something like create the file or report this
    } catch (System.Exception ex) {
       // do something else
    }
    
  • Kaso (unregistered) in reply to shoddycoder

    This is usually to avoid "variable may not have been initialized" warnings.

    The FileStream would be read while uninitialized in the finally otherwise.

  • Friedrice the Great (unregistered) in reply to Anon
    Anon:
    Gabe:
    I've used this exact snippet... The key thing in my situation though, is that there is only one thing that will be locking the file so race conditions aren't a big deal.

    Not a big deal - until it is. So why not just solve it properly in the first place? Its not like the solution is difficult.

    All solutions are difficult. If they were easy, we wouldn't have any problems!

  • Friedrice the Great (unregistered) in reply to Z
    Z:
    spamcourt:
    Mike:
    Kids are TRWTF, AJ. I mean, what useful purpose do they serve, other than to make a mess of the place you had to move to because his bachelor pad wasn't "homey" enough, destroy all the expensive crap you made him buy you, and leave the lights and TV on until they're old enough to finance a major drug addiction?
    They are literally the most annoying thing that you'll ever find, and they are going to make your life hell for many years. Unfortunately humans are programmed to want them anyways...

    No, chatboard trolls are the most annoying thing you'll ever find. Although you can make a pretty convincing argument that trolls are not really a lifeform, and they can always be safely ignored, you still have to step over the stinking mess they leave on the carpet. No, wait; that was cats.

    No, that came from spammers, or Akismet.

  • (cs) in reply to jay
    jay:
    But the point of the article seems to be to ridicule the idea of retrying repeatedly after a failure.
    No, the point of the article is that the code is "waking the file up" just to find out whether it's "awake", then letting it "go back to sleep" for an indeterminate amount of time before it attempts to access it. In other words, the race condition (or rather, the uselessness of the test open) is indeed the point.
  • (cs) in reply to Kaso
    Kaso:
    This is usually to avoid "variable may not have been initialized" warnings.

    The FileStream would be read while uninitialized in the finally otherwise.

    Variable uninitialized is actually a compiler error. And if you try to read from it this way you'll get a null reference exception, so no help. This does nothing positive.

  • Kabi (unregistered) in reply to Sutherlands
    Sutherlands:
    Kaso:
    This is usually to avoid "variable may not have been initialized" warnings.

    The FileStream would be read while uninitialized in the finally otherwise.

    Variable uninitialized is actually a compiler error. And if you try to read from it this way you'll get a null reference exception, so no help. This does nothing positive.
    And exactly that is the reason why the first line in the finally block is a check against null. Last time i wrote that construct no null reference exception was thrown.

    But if I remember correctly, C# has using blocks specifically for this reason.

  • sroughley (unregistered)

    No one commenting on TRWTF: File system access in the 'BusinessLogic' layer! SoC anyone?

  • EuroGuy (unregistered) in reply to herby
    herby:
    Sorry, the real purpose of kids (and grandkids for that matter is to pay for the government you have now. This includes things like Social Security (misnomer), and Medicare (another joke). The big reason though is so they will take care of you in your advancing age.

    Gotta love how some people can turn any thread on programming choices into a political rant.

  • Krzysiek (unregistered) in reply to Cbuttius
    Cbuttius:
    It is the correct way to check if a file is locked if, presumably, the purpose is that if it is not locked you open it and perform some operation with it.

    Because if you call some method that returns a boolean that says it is not locked, then you may try opening it only to find that a race condition has occurred and it now really is locked.

    Inception FTW:

    if (!FileLocked(fileName))
    {
        if (!FileLocked(fileName)) // really not locked?
        {
            writeToFile(data);
        }
    }

    Application of recursion to do arbitrary inception depth is left as an exercise to the reader. ;-)

  • Harry Johnston (unregistered) in reply to Medinoc

    @Medinoc: System.Io.File doesn't appear to have an Access member, so I'm not sure what you're thinking of. There doesn't seem to be any method to check whether a file is already in use. For that matter, I don't think there's any such method in the underlying Win32 API, short of using unsupported functions to enumerate all the handles in the system.

  • Rogue_Leader (unregistered)

    "A few months ago she was working long hours on a migration to a new codebase, so she made up the lost sleep on the weekends"

    AJ needs to find another job that doesn't raep her weekends.

  • (cs) in reply to ZPedro
    ZPedro:
    Hmm, I work more in the context of POSIX filesystem APIS (open(), creat(), read() and the like) so by "try then handle failure" I did not necessarily mean something that could throw exceptions, but things may be different in the C#/.NET world. Is it really impossible to try/handle failure with filesystem operations without throwing an exception in case of failure in .NET? If so, then it's a Microsoft/.NET WTF.
    I wholeheartedly agree, it's a WTF that the base class library doesn't provide a way to treat failure to open a file as non-exceptional. As far as I know, the same applies to Java.
    Swedish tard:
    Unless you have some stupendously fast harddrives, I'd wager that the time spent with throwing an exception is easily eaten by the time spent doing I/O, thus I dub this worry as premature optimization.
    I dare to assume here that the OS will not perform the same I/O twice without caching the result, but I may be mistaken.
    Harry Johnston:
    @Medinoc: System.Io.File doesn't appear to have an Access member, so I'm not sure what you're thinking of. There doesn't seem to be any method to check whether a file is already in use. For that matter, I don't think there's any such method in the underlying Win32 API, short of using unsupported functions to enumerate all the handles in the system.
    My bad, I appear to have confused the POSIX access() function and the System.IO.File.Exists() method.
  • jay (unregistered) in reply to Scarlet Manuka
    Scarlet Manuka:
    jay:
    But the point of the article seems to be to ridicule the idea of retrying repeatedly after a failure.
    No, the point of the article is that the code is "waking the file up" just to find out whether it's "awake", then letting it "go back to sleep" for an indeterminate amount of time before it attempts to access it. In other words, the race condition (or rather, the uselessness of the test open) is indeed the point.

    Hmm, that's not the impression I got. If that's what the writer meant, then I agree 100%. I could go back and re-read the article to see if I just read it too hastily the first time and mis-interpreted. But I don't care enough to make the effort.

  • jay (unregistered) in reply to EuroGuy
    EuroGuy:
    herby:
    Sorry, the real purpose of kids (and grandkids for that matter is to pay for the government you have now. This includes things like Social Security (misnomer), and Medicare (another joke). The big reason though is so they will take care of you in your advancing age.

    Gotta love how some people can turn any thread on programming choices into a political rant.

    We should try to balance that by going to political web sites and making posts about programming.

  • jay (unregistered) in reply to spamcourt
    spamcourt:
    Mike:
    Kids are TRWTF, AJ. I mean, what useful purpose do they serve, other than to make a mess of the place you had to move to because his bachelor pad wasn't "homey" enough, destroy all the expensive crap you made him buy you, and leave the lights and TV on until they're old enough to finance a major drug addiction?
    They are literally the most annoying thing that you'll ever find, and they are going to make your life hell for many years. Unfortunately humans are programmed to want them anyways...

    No, the MOST annoying this is people who constantly whine about children, the neighbors, their boss, and VB programmers.

  • Grumbler (unregistered)

    TRWTF here is the writing. Among other awkwardly phrased sentences is the following gem:

    The following Monday, AJ performed a code review of some licensed software that corporate bought for a princely sum for the project.

    "for a princely sum": This contributes heavily to the awkwardness because of the daisy-chained use of the word 'for' later in the sentence. Worse, we don't need this information. It adds nothing to the story and it isn't relevant to the WTF. I am guessing the implication was supposed to be that because the software was expensive it should have a certain quality. However, it misses its mark. In any case, we all already know better by virtue of being on this site.

    "for the project": For what project? We can conclude that the writer means the code migration mentioned at the beginning of the article, but the writer is expecting the reader to do too much work. Like above, it isn't even necessary to include the information. It isn't relevant that the software was purchased for the migration. (It really isn't even relevant that AJ was working on the migration at all if she was doing a code review on something else.) Even if the writer feels it is necessary to include that information, the use of the word "migration" instead of "project" would have been much clearer.

    "that corporate bought": Corporate bought AJ's performance of a code review? They bought the software that they also licensed? Unclear.

    Rewritten: "The following Monday, AJ performed a code review of some newly-licensed software."

    Beyond the awkward phrasing, the general flow of the article left a lot to be desired. Specifically the transitions between the family parts and the work parts were choppy. I would leave off the bit at the end about her returning home. It adds nothing.

  • chris (unregistered) in reply to ubersoldat
    ubersoldat:
    Why, if C# looks exactly as Java, do method names start with upper-case? Is this some MS way of trying to be "special"? This is just retarded.
    Without looking it up, my guess is that the standard of upper case method names was firmly established in the C++ Microsoft Foundation Classes and they didn't want to change the standard in .NET since Visual C++ was also moving to .NET.
  • (cs) in reply to Krzysiek
    Krzysiek:
    Cbuttius:
    It is the correct way to check if a file is locked if, presumably, the purpose is that if it is not locked you open it and perform some operation with it.

    Because if you call some method that returns a boolean that says it is not locked, then you may try opening it only to find that a race condition has occurred and it now really is locked.

    Inception FTW:

    if (!FileLocked(fileName))
    {
        if (!FileLocked(fileName)) // really not locked?
        {
            writeToFile(data);
        }
    }

    Application of recursion to do arbitrary inception depth is left as an exercise to the reader. ;-)

    Known as the WTF method of double-checked locking.

  • Jason (unregistered)

    I do know of at least one situation in which the "double check" makes some sense.

    In Java, "File.exists()" can sometimes return FALSE, even when the file does actually exist - http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5003595

    This is due to improper handling of stale NFS file handles. A second call to File.exists() will usually give the correct result.

  • Norman Diamond (unregistered)

    TRIsFileLocked returns a boolean: True, False, FileNotFound

  • Norman Diamond (unregistered)

    In a country whose government sometimes cares about reducing racism, a company sent its programmers to a training course to teach them that different races are equally deserving of respect. (And maybe that WTFs are WTFs because they're WTFs not because of the person's race? Nah, that would be asking too much.)

    So, why did the company have to send its programmers to a training course on racial relations?

    Well, of course, because one time a development manager was called out of a meeting, and when he returned to the meeting he explained: "I had to deal with a race condition" ... and an HR droid heard it.

  • Krzysiek (unregistered) in reply to Jason
    Jason:
    I do know of at least one situation in which the "double check" makes some sense.

    In Java, "File.exists()" can sometimes return FALSE, even when the file does actually exist - http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5003595

    This is due to improper handling of stale NFS file handles. A second call to File.exists() will usually give the correct result.

    In that case TRWTF is the function that usually gives the correct result the second time...

  • JJ (unregistered) in reply to shoddycoder
    shoddycoder:
    FileStream stream = null;

    Never seen the point of this, the object is null if uninitilized anyway and you've taken out a compiler check (in Java) by intializing to null

    It's required by C#. If you didn't initialize the variable, you'd get a "Use of unassigned local variable 'stream'" error at compile.

  • JJ (unregistered) in reply to chris
    chris:
    ubersoldat:
    Why, if C# looks exactly as Java, do method names start with upper-case? Is this some MS way of trying to be "special"? This is just retarded.
    Without looking it up, my guess is that the standard of upper case method names was firmly established in the C++ Microsoft Foundation Classes and they didn't want to change the standard in .NET since Visual C++ was also moving to .NET.
    Without looking it up, my guess is that lots of folks at Microsoft agree with me that camelCase is horrifically ugly.
  • The Big Picture Thinker (unregistered) in reply to Talib
    Talib:
    Well surprisingly this seems to be the correct way for checking if a file is in use

    Nope...

    What's "correct" is trying to open it to see if it's locked. And that's debatable.

    However, this example opens it to see if it's locked. Then closes it immediately. Then still ASSUMES it's not locked and opens it again for writing.

    At any time, the OS could have descheduled that program and another program could be running that also had the same file queued for opening.

Leave a comment on “The Right Way to Find a File”

Log In or post as a guest

Replying to comment #:

« Return to Article