What would be the easiest way to separate the directory name from the file name when dealing with SaveFileDialog.FileName in C#?
Use:
System.IO.Path.GetDirectoryName(saveDialog.FileName)
(and the corresponding System.IO.Path.GetFileName). The Path class is really rather useful.
You could construct a FileInfo object. It has a Name, FullName, and DirectoryName property.
var file = new FileInfo(saveFileDialog.FileName);
Console.WriteLine("File is: " + file.Name);
Console.WriteLine("Directory is: " + file.DirectoryName);
The Path object in System.IO parses it pretty nicely.
Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String.LastIndexOf; for example:
string filename = dialog.Filename;
string path = filename.Substring(0, filename.LastIndexOf("\"));
string file = filename.Substring(filename.LastIndexOf("\") + 1);
Related
For searching files in a directory, I am using this snippet of code :
string targetToCopy = ConfigurationManager.AppSettings["drive"] + element.Element("categorie").Value.ToString().Replace(" / ", #"\");
DirectoryInfo directoryToCopy = new DirectoryInfo(targetToCopy);
I create the path with this string targetToCopy, I parse the string in DirectoryInfo for using the directoryToCopy.GetFiles() method.
This method searches files with path, and when I use this in my loop, I get an error:
System.NotSupportedException : 'The format of the given path is not supported.'
I don't know what this error means, but if you know how to solve the problem.
Thank you and good luck :)
I determined the problem by outputting my path to a log file, and finding it not formatting correctly. Correct for me was quite simply:
DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.FullName.ToString());
There is a space before the / in Replace(" / ", #"\") therefore String.Replace transformation is not in effect
Updated code
string targetToCopy = ConfigurationManager.AppSettings["drive"] + element.Element("categorie").Value.ToString().Replace("/ ", #"\");
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following
string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);
In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?
Things I have
1.) File name without extension in
string filename = ddl.SelectedItem.Text;
2.) Path where the file is located
string path = "F:\\WorkingCopy\\files\\" + filename
I am trying to get the file extension with these . Can any one suggest on this?
You can use Directory.EnumerateFiles() like this:
string path = "F:\\WorkingCopy\\files\\";
string filename = ddl.SelectedItem.Text;
string existingFile = Directory.EnumerateFiles(path, filename + ".*").FirstOrDefault();
if (!string.IsNullOrEmpty(existingFile))
Console.WriteLine("Extension is: " + Path.GetExtension(existingFile));
Directory.EnumerateFiles searches the path for files like filename.*. Path.GetExtension() returns the extension of the found file.
In general, I prefer to use EnumerateFiles() instead of GetFiles because it returns an IEnumerable<string> instead string[]. This suggests that it only returns the matching files as needed instead searching all matching files at once. (This doesn't really matter in your case, just a general note).
Use the Directory.GetFiles() method. Something like this
string[] files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename+".*");
This should get you an array of filenames with the same filename but different extensions. If you have only one, then you can always use the first one.
You can use Directory.GetFiles Method:
string result = Directory.GetFiles(path, filename + ".*").FirstOrDefault();
see here
here " * " is the WildCard and will search for the Filename starts with YourFileName.
you can achieve that with followed by line
try
{
var extensions = new List<string>();
var files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename + ".*", System.IO.SearchOption.TopDirectoryOnly);
foreach (var tmpfile in files)
extensions.Add(Path.GetExtension(tmpfile));
}
catch (Exception ex)
{
throw ex;
}
will this help you?
You can simply split them by dot, For example, try this code
string folder = #"F:\\WorkingCopy\\files\\";
var files = System.IO.Directory.GetFiles(folder, filename + ".*");
if (files.Any())
{
string ext = System.IO.Path.GetExtension(files.First()).Substring(1);
}
This code gives me result that the extension for this is txt file.
I'm new to C# and struggle with string parsing. I have a string like this:
C:\User\Max\Pictures\
And I got multiple file paths:
C:\User\Max\Pictures\car.jpg
C:\User\Max\Pictures\trains\train.jpg
How can I strip the base path from those file paths to get:
car.jpg
trains\train.jpg
Something like this failed:
string path = "C:\\User\\Max\\Pictures\\";
string file = "C:\\User\\Max\\Pictures\\trains\\train.jpg";
string newfile = file.Substring(file.IndexOf(path));
You want to get the substring of file after the length of path:
string newfile = file.Substring(path.Length);
Note that it's a good idea to use Path methods like Path.GetFileName() when dealing with file paths (though it's not good applyable to the "train" example).
The other answer would be to replace your path with an empty string :
string filePath = file.Replace(path, "");
There are special classes to handle filepaths
var filePath = new FileInfo("dd");
In filePath.Name is the filename of the file whitout directory
So for your scenario you want to strip base dir. So you can do this
var filePath = new FileInfo(#"c:\temp\train\test.xml");
var dir = filePath.FullName.Replace(#"c:\temp", String.Empty);
I have a String Path to output a .ZIP file String path = #"C:\TEMP\test.zip"; and I am looking to five the file name a date stamp. Example, test_TodayDate.ZIP.
There's a way to achieve this?
Thanks
You can create your own variable, like this,
// gets the file name without extension
var fileName = Path.GetFileNameWithoutExtension(path);
// create the new file name
var newFileName = fileName + "_" + DateTime.Now + ".zip";
Now save the new file generated, and name this file as the newFileName it will have the DateTime in the name.
You can do:
string filePath = #"C:\TEMP\test.zip";
string finalPath = Path.Combine(Path.GetDirectoryName(filePath),
Path.GetFileNameWithoutExtension(filePath)
+ DateTime.Now.ToString("yyyyMMddHHmmss")
+ Path.GetExtension(filePath));
First Get File name without extension and add your Time Stamp, Then concatenate file extension,
Then get Current directory for the file path
Use Path.Combine to combine directory and new file name
If i have the following directory structure:
Project1/bin/debug
Project2/xml/file.xml
I am trying to refer to file.xml from Project1/bin/debug directory
I am essentially trying to do the following:
string path = Environment.CurrentDirectory + #"..\..\Project2\xml\File.xml":
what is the correct syntax for this?
It's probably better to manipulate path components as path components, rather than strings:
string path = System.IO.Path.Combine(Environment.CurrentDirectory,
#"..\..\..\Project2\xml\File.xml");
Use:
System.IO.Path.GetFullPath(#"..\..\Project2\xml\File.xml")
string path = Path.Combine( Environment.CurrentDirectory,
#"..\..\..\Project2\xml\File.xml" );
One ".." takes you to bin
Next ".." takes you to Project1
Next ".." takes you to Project1's parent
Then down to the file
Please note that using Path.Combine() might not give you the expected result, e.g:
string path = System.IO.Path.Combine(#"c:\dir1\dir2",
#"..\..\Project2\xml\File.xml");
This results in in the following string:
#"c:\dir1\dir2\dir3\..\..\Project2\xml\File.xml"
If you expect the path to be "c:\dir1\Project2\xml\File.xml", then you might use a method like this one instead of Path.Combine():
public static string CombinePaths(string rootPath, string relativePath)
{
DirectoryInfo dir = new DirectoryInfo(rootPath);
while (relativePath.StartsWith("..\\"))
{
dir = dir.Parent;
relativePath = relativePath.Substring(3);
}
return Path.Combine(dir.FullName, relativePath);
}