Go Back   Computer Forums > General Computing > Programming
Click Here to Login
Join Computer forums Today


Reply
 
Thread Tools Search this Thread Display Modes
 
Old 01-18-2009, 02:37 PM   #1
Baseband Member
 
Join Date: Nov 2008
Posts: 91
Default finding text files in C# console applications

In C# console applications, isn't there a simpler way than handling exceptions to just find out if a text file of a given name exists in the current directory? I'm talking about something along the same lines as the following methods:

create text file:
Code:
StreamWriter SW = File.CreateText ("MyFile.txt");
open existing text file:
Code:
StreamReader SR = File.OpenText ("MyFile.txt");
append to text file:
Code:
StreamWriter SW  = File.AppendText ("MyFile.txt");
__________________

BobLewiston is offline   Reply With Quote
Old 01-18-2009, 07:32 PM   #2
Fully Optimized
 
UK31337's Avatar
 
Join Date: Feb 2005
Posts: 2,776
Default Re: finding text files in C# console applications

I would just check if the file exists before setting up the StreamReader etc. The .Net framework provides a means for you to do this.

Code:
string fileName = "MyFile.txt"; // The path of the file

if (File.Exists(fileName)) // If the file exists
{

// Shizzle

}
else
{
Console.Writeline("Oh cock.");
}
Hope that helps, unless I misunderstood you.

http://msdn.microsoft.com/en-us/libr...le.exists.aspx
__________________

__________________
Master of common sense. If you don't like it, stop reading.
UK31337 is offline   Reply With Quote
Old 02-01-2009, 09:40 AM   #3
Baseband Member
 
Join Date: Oct 2008
Posts: 21
Default Re: finding text files in C# console applications

You have to ensure the file exists and the file is accessible to your program.

Write a [reusable] function that attempts to open the file for reading and uses a try-catch block. Have it return a bool. Use this function to test if the file can be opened before you attempt to open it for actual reading. This way, you only have to write the try-catch block once, namely when you write the function. I do C++ not C#, but maybe that'll help?

I would also learn about all the methods dealing with opening files in C#. There are probably lots of member functions for the objects dealing with this.
miked8887 is offline   Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off



All times are GMT -5. The time now is 07:15 AM.


Powered by vBulletin® Version 3.8.8 Beta 4
Copyright ©2000 - 2017, vBulletin Solutions, Inc.
Search Engine Friendly URLs by vBSEO 3.6.0