Jump to content


 


Register a free account to unlock additional features at BleepingComputer.com
Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.


Click here to Register a free account now! or read our Welcome Guide to learn how to use this site.

Photo

finding text files in C# console applications


  • Please log in to reply
2 replies to this topic

#1 BobLewiston

BobLewiston

  • Members
  • 69 posts
  • OFFLINE
  •  
  • Local time:11:45 PM

Posted 18 January 2009 - 02:33 PM

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:
StreamWriter SW;
SW = File.CreateText ("MyFile.txt");
open existing text file:
StreamReader SR;
SR = File.OpenText ("MyFile.txt");
append to text file:
StreamWriter SW;
SW  = File.AppendText ("MyFile.txt");


BC AdBot (Login to Remove)

 


#2 groovicus

groovicus

  • Security Colleague
  • 9,963 posts
  • OFFLINE
  •  
  • Gender:Male
  • Location:Centerville, SD
  • Local time:09:45 PM

Posted 18 January 2009 - 02:59 PM

Easier than what?

#3 Billy O'Neal

Billy O'Neal

    Visual C++ STL Maintainer


  • Malware Response Team
  • 12,304 posts
  • OFFLINE
  •  
  • Gender:Male
  • Location:Redmond, Washington
  • Local time:08:45 PM

Posted 18 January 2009 - 05:43 PM

You should ALWAYS handle exceptions when working with File I/O. Just because the file exists doesn't mean that opening it will succeed.

If you only need to check if the file exists, try the
Microsoft.VisualBasic.FileIO.FileSystem.FileExists() method.
http://msdn.microsoft.com/en-us/library/mi...fileexists.aspx

Billy3

EDIT: Removed extra .

EDIT2:Also, C# by default doesn't try the current directory if I'm not mistaken. You'd need to enumerate the current directory.

Edited by groovicus, 18 January 2009 - 07:21 PM.
Edited post since Billy couldn't find the edit button. :)

Twitter - My statements do not establish the official position of Microsoft Corporation, and are my own personal opinion. (But you already knew that, right?)
Posted Image




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users