by kirupa |
29 March 2007In the
previous page you learned how to write files, and I
began talking about how to check if a file exists. In this
page, I'll continue from where we left off and talk more
about checking whether files exist.
Something to remember is that a file is created or
overwritten when your StreamWriter is initialized with the
path to your file. Therefore, something like the following
will not work like you would want to:
- string
filePath
=
"C:\\Users\\Kirupa\\Desktop\\foo.txt";
-
- StreamWriter
foo =
new
StreamWriter(filePath);
-
- if
(File.Exists(filePath))
- {
- // File exists
- }
- else
- {
- // File does not exist
- }
The reason is that the moment your StreamWriter object
foo is initialized, the file pointing to by
filePath will be
created or overwritten. Our File.Exists boolean will always
return true because no matter what you reasonably do, a file
at filePath will exist.
If you want to avoid overwriting an existing file, the
following approach works better:
- string
filePath
=
"C:\\Users\\Kirupa\\Desktop\\foo.txt";
-
- StreamWriter
foo;
-
- if
(File.Exists(filePath))
- {
- // File exists
- // Don't do anything.
- }
- else
- {
- // File does not exist
- foo
=
new StreamWriter(filePath);
- foo.Write("Blarg.
Zorb. Zeeb. Foo.");
- foo.Close();
- }
In the above code, a file is created only if
File.Exists
returns false. Notice that our StreamWriter object foo isn't
being initialized until our code reaches the
File.Exists ==
false condition.
Both the StreamReader and StreamWriter classes work
asynchronously. That's a cool sounding word that basically
means that you can do other things when using StreamReader
or StreamWriter. To take a real world example, if you were
opening a huge text file, you can continue to use your
application and everything will seem to work fine without
suffering delays or lags associated with reading your file.
If both of those classes were not asynchronous, then you would have to use Threads to
ensure any time consuming reading or writing task operates
semi-independently from other tasks. Threads is an
interesting topic that I will save for a later article.
Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!
|