Can I find a file by filename only (i.e. extension unknown) - c#

We have a network folder that is the landing place for csv files processed by different servers. We alter the extension of the csv files to match the server that processed the file; for instance a file with the name FooBar that was process by Server1 would land in the network share with the name FooBar.Server_1.
The information I have available to to me is file name: FooBar and the path to the share. I am not guaranteed the extension as there are multiple servers sending csv files to the network share. I am guaranteed that there will only be one FooBar file in the share.
Is there a method in .net 2.0 that can be used to get the extension of the csv armed only with the path and filename? Or do I need to craft my own?

Directory.GetFiles(NETWORK_FOLDER_PATH, "FooBar.*")[0] will give you the full path.
Path.GetExtension will give you the extension.
If you want to put it all together:
string extension = Path.GetExtension(
Directory.GetFiles(NETWORK_FOLDER_PATH, "FooBar.*")[0]);

This should do the trick:
string[] results = System.IO.Directory.GetFiles("\\\\sharepath\\here", "FooBar.*", System.IO.SearchOption.AllDirectories);
if(results.Length > 0) {
//found it
DoSomethingWith(results[0]);
} else {
// :(
}

DirectoryInfo di = new DirectoryInfo(yourPath)
{
FileInfo[] files = di.GetFiles(FooBar.*);
}

If you know the directory where the file will reside you can use DirectoryInfo.GetFiles("SearchPattern"): DirectoryInfo.GetFiles("FooBar.*")

Related

How to check if a String Path is a 'File' or 'Directory' if path doesn't exist?

I have a function that automatically creates a specified Path by determining whether the String Path is a File or Directory.
Normally, i would use this if the path already exists:
FileAttributes attributes = File.GetAttributes("//Path");
if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
Directory.CreateDirectory("//Path");
}
But what if it doesn't? How to check whether the String Path is a File or Directory if it doesn't exist?
If files in your scenario must have extensions then you could use this method.
NOTE: It is legal in windows to have periods in directories, but this was mostly introduced for cross operating system compatibility of files. In strictly windows environments it is considered bad form to have files without extensions or to put periods or spaces in directory names. If you do not need to account for that scenario then you could use this method. If not you would have to have some sort of flag sent through the chain or a structure to identify the intent of the string.
var ext = System.IO.Path.GetExtension(strPath);
if(ext == String.Empty)
{
//Its a path
}
If you do not need to do any analysis on file type you can go as simple as:
if(System.IO.Path.HasExtension(strPath))
{
//It is a file
}
The short answer is that there is no 100% way to distinguish a folder from a file by path alone. A file does not have to have a file extension, and a folder can have periods in its name (making it look like a file extension).

How do i access and create txt files in the same directory as the program in c#

http://pastebin.com/DgpMx3Sx
Currently i have this, i need to find a way to make it so that as opposed to writing out the directory of the txt files, i want it to create them in the same location as the exe and access them.
basically i want to change these lines
string location = #"C:\Users\Ryan\Desktop\chaz\log.txt";
string location2 = #"C:\Users\Ryan\Desktop\chaz\loot.txt";
to something that can be moved around your computer without fear of it not working.
If you're saving the files in the same path as the executable file then you can get the directory using:
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Normally you wouldn't do that, mostly because the install path will be found in the Program Files folders, which require Administrative level access to be modified. You would want to store it in the Application Data folder. That way it is hidden, but commonly accessible through all the users.
You could accomplish such a feat by:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullPath = Path.Combine(path, #"NameOfApplication");
With those first two lines you'll always have the proper path to a globally accessible location for the application.
Then when you do something you would simply combine the fullPath and the name of the file you attempt to manipulate with FileStream or StreamWriter.
If structured correctly it could be as simple as:
private static void WriteToLog(string file)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullPath = Path.Combine(path, #"NameOfApplication");
// Validation Code should you need it.
var log = Path.Combine(fullPath, file);
using(StreamWriter writer = new StreamWriter(log))
{
// Data
}
}
You could obviously structure or make it better, this is just to provide an example. Hopefully this points you in the right direction, without more specifics then I can't be more help.
But this is how you can access data in a common area and write out to the file of your choice.

write to the file system in a directory

I would like to write to the file system in a directory C: \ directory name, for the moment I have this code:
if (! System.IO.File.Exists (HttpContext.Current.Server.MapPath (filename)))
{
TXTFile = new System.IO.StreamWriter (HttpContext.Current.Server.MapPath (filename));
}
else
{
TXTFile = System.IO.File.AppendText (HttpContext.Current.Server.MapPath (filename));
}
but in this way writes on the application folder.
How to fix it?
Just do
Path.Combine(#"C:\", filename)
instead of
HttpContext.Current.Server.MapPath (filename)
Ensure your application has write access to the destination.
It seems you are doing this from a web application?
Although it is possible (with the correct rights) to write to the C:\ root, it is not very good practice.
You'd probably be safer to save it somewhere else. Also look into this method Environment.GetFolderPath

Get attributes of all files under a directory while accessing the directory only

I'm trying to write a function in C# that gets a directory path as parameter and returns a dictionary where the keys are the files directly under that directory and the values are their last modification time.
This is easy to do with Directory.GetFiles() and then File.GetLastWriteTime(). However, this means that every file must be accessed, which is too slow for my needs.
Is there a way to do this while accessing just the directory? Does the file system even support this kind of requirement?
Edit, after reading some answers:
Thank you guys, you are all saying pretty much the same - use FileInfo object. Still, it is just as slow to use Directory.GetFiles() (or Directory.EnumerateFiles()) to get those objects, and I suspect that getting them requires access to every file. If the file system keeps last modification time of its files in the files themselves only, there can't be a way to extract that info without file access. Is this the case here? Do GetFiles() and EnumerateFiles() of DirectoryInfo access every file or get their info from the directory entry? I know that if I would have wanted to get just the file names, I could do this with the Directory class without accessing every file. But getting attributes seems trickier...
Edit, following henk's response:
it seems that it really is faster to use FileInfo Object. I created the following test:
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now);
foreach (string file in Directory.GetFiles(#"\\169.254.78.161\dir"))
{
DateTime x = File.GetLastWriteTime(file);
}
Console.WriteLine(DateTime.Now);
DirectoryInfo dirInfo2 = new DirectoryInfo(#"\\169.254.78.161\dir");
var files2 = from f in dirInfo2.EnumerateFiles()
select f;
foreach (FileInfo file in files2)
{
DateTime x = file.LastWriteTime;
}
Console.WriteLine(DateTime.Now);
}
For about 800 files, I usually get something like:
31/08/2011 17:14:48
31/08/2011 17:14:51
31/08/2011 17:14:52
I didn't do any timings but your best bet is:
DirectoryInfo di = new DirectoryInfo(myPath);
FileInfo[] files = di.GetFiles();
I think all the FileInfo attributes are available in the directory file records so this should (could) require the minimum I/O.
The only other thing I can think of is using the FileInfo-Class. As far as I can see this might help you or it might read the file as well (Read Permissions are required)

how to access all filenames from a remote server folder - c#?

I have many images on remote server say images.foo.com/222 & i want to access file names of all files that resides in the folder 222 on images.foo.com/.
i have tried following code but getting error "virtual path is not valid" :
imageserver = http://images.foo.com/222;
DirectoryInfo di = new DirectoryInfo(imageserver); // line giving exception
FileInfo[] rgFiles = di.GetFiles();
string simagename = "";
if (rgFiles.Count() > 0)
{
foreach (FileInfo fi in rgFiles)
{
//collect each filename from here
}
}
Please help
thanks in advance
gbaxi
DirectoryInfo need a UNC path of type "\\fileserver\images"
A http address will not work
You can't access a directory residing on the web with the DirectoryInfo class. Instead, use the WebRequest class to get a list from the URL and get the files from that list.
The problem is that HTTP does not have a clear interface on how a directory listing is being displayed. There are roughly two choices:
Parse the HTML retrieved through a WebRequest, but you won't get things like creation/modification time and user;
Go with a different mechanism to retrieve the file details like FTP or File share.

Categories