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.
Need Help?
If you have questions, need some assistance on this topic, or just want to
chat - please drop by our friendly forums
and post your question. There are a lot of knowledgeable and witty people who
would be happy to help you out. Plus, we have a
large collection of smileys
you can use

Share
Did you enjoy reading this and found it useful? If so, please share it with
your friends:
If you didn't like it, I always like to hear how I can do better next time.
Please feel free to contact me directly at kirupa[at]kirupa.com.
Cheers!
|