Why am I getting this error? I am using the correct path.
Problem : You are providing the Path of File
Solution : You need to provide the path of Directory to get all the files in a given Directory based on your search pattern.
From MSDN: Directory.GetFiles()
Returns the names of files (including their paths) that match the
specified search pattern in the specified directory.
Try this:
string directoryName = Path.GetDirectoryName(e.FullPath);
foreach(String filename in Directory.GetFiles(directoryName,"*.eps"))
{
//your code here
}
You want the directory, not the filename.
At the moment, the value of e.FullPath is "C:\\DigitalAssets\\LP_10698.eps". It should be "C:\\DigitalAssets".
string[] fileNames = Directory.GetFiles(string path) requires a directory, you are giving it a directory + filename.
MSDN:
Returns the names of files (including their paths) that match the
specified search pattern in the specified directory.
foreach(string filename in Directory.GetFiles(e.FullPath, "*.eps"))
{
// For this to work, e.FullPath needs to be a directory, not a file.
}
You can use Path.GetDirectoryName():
foreach(string filename in Directory.GetFiles(Path.GetDirectoryName(e.FullPath), "*.eps"))
{
// Path.GetDirectoryName gets the path as you need
}
You could create a method:
public string GetFilesInSameFolderAs(string filename)
{
return Directory.GetFiles(Path.GetDirectoryName(filename), Path.GetExtension(filename));
}
foreach(string filename in GetFilesInSameFolderAs(e.FullPath))
{
// do something with files.
}
e.FullPath seems to be a file, not a directory. If you want to enumerate *.eps files, the first argument to GetFiles should be a directory path: #"C:\DigitalAssets"
the first argument of GetFiles should be only "C:\DigitalAssets"
e.FullPath include the file name in it.
Directory.GetFiles used to get file names from particular directory. You are trying to get files from file name which is not valid as it gives you error. Provide directory name to a function instead of file name.
You can try
Directory.GetFiles(System.IO.Path.GetDirectoryName(e.FullPath),"*.eps")
For deleting files from a directory
var files = Directory.GetFiles(directory)
foreach(var file in files)
{
File.Delete(file);
}
In short to delete the file use
File.Delete(filePath);
and to delete the directory
Directory.Delete(directoryPath)
Related
I am trying to get the file path and file name of I file I upload in a folder. I have the paths like so:
string path = Path.Combine(_webHost.ContentRootPath, "Uploads\\ZipFiles\\");
string extractPath = Path.Combine(_webHost.ContentRootPath, "Uploads\\ExtractedFiles\\");
I upload my file in path and I unzip the file in extractPath.
string fullPath = Path.GetFullPath(extractPath);
string fileName = Path.GetFileName(extractPath);
fullPath returns the correct path but fileName is empty. I don't get the file name.
I am trying to get something like this
var dbfPath = "C://ExtractedFiles//fileName.jpg";
I was planning on getting the file path in one variable and the file name in another and then concatenate them but I can't get the file name. What's the best way to do this?
To get the files in the ExtractedFiles folder :
string[] files = Directory.GetFiles(extractPath)
If your zip have folders inside, and you want to get all the file inside them recursively use :
string[] files = Directory.GetFiles(extractPath, "*.*", SearchOption.AllDirectories)
I receive every day a file with a specific pattern and extension, which I want to run under certain process. I want to check if there is any file in my folder, because otherwise I will do another task. So far I found that you can use a Script Task and do a File.Exist. However, I'm doing something wrong because it doesn't take the * as a wildcard.
Devoluciones_source is "C:\Users\us1\Folder\"
FileToSearch is "return"
My files:
return_20200102.csv
return_20200203.csv
String Filepath = Dts.Variables["$Project::Devoluciones_source"].Value.ToString() + Dts.Variables["User::FileToSearch"].Value.ToString() + "*csv";
if (
File.Exists(Filepath))
{
Dts.Variables["User::IsFound"].Value = 1;
}
I don't think File.Exits() accepts wildcards, it checks the literal filepath and will return false because C:\Users\us1\Folder\*.csv is not found.
What you could do instead is get the files in the folder C:\Users\us1\Folder\ and checking those agains a searchPattern using Directory.GetFiles(path, searchPattern)
Like this:
string dirPath = Dts.Variables["$Project::Devoluciones_source"].Value.ToString();
string fileName = Dts.Variables["User::FileToSearch"].Value.ToString();
// if you want to make sure the directory exists:
if(Directory.Exists(dirPath) {
string[] files = Directory.GetFiles(dirPath, fileName + "*.csv");
if(files.lenght > 0) {
// you can now iterate over each file that is found in the users directory that matches your pattern and do your logic.
}
}
Some more info on the Directory.GetFiles method: Directory.GetFiles on docs.Microsoft.com
Some more info on the Files.Exists method: Directory.GetFiles on docs.Microsoft.com
I use the following code to take all the files from a directory and search for a specific file:
string [] fileEntries = Directory.GetFiles("C:\\uploads");
foreach(string fileName in fileEntries)
if (fileName.Contains(name))
PicturePath = fileName;
where "name" is a string which I get from DB.
It seems to work to an extend but if my file contains a space in fileName it only takes the first string from fileName which is the first string before the white space, ignoring th rest. How can i take the full fileName (as well as the path to that file accordingly).
For example: I have a file named "ALEXANDRU ALINA.jpg" inside uploads and in name i have the string "ALEXANDRU ALINA". When I run that code (writing the PicturePath) it displays just "ALEXANDRU".
This might be what you're looking for:
string[] fileEntries = Directory.GetFiles("C:\\uploads");
foreach (string fileName in fileEntries)
{
FileInfo fi = new FileInfo(fileName);
if (fi.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)) PicturePath = fileName;
}
What you're attempting to do is find the target file name within the whole path, but the method you're using could produce errors (what if the name is contained within part of the folder path?). By using the System.FileInfo class and its Name property, which is the file name only (not the full file path which includes the containing folder path), you won't be needlessly searching any part of the folder path.
i want to create C# mass file renamer, here is my UI
i have created tes folder, inside of tes there's a file which is 1.txt.
i want to create my program to add prefix and suffix to the files, so 1.txt will become
prefix1suffix
but then i got an error
it's said file already exist though there's only one file on tes folder, which is 1.txt how do i make it work ? where's the error comes from ?
i have tried the following code
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
File.Move(f.FullName,"stackoverflow");
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
and it returns same error as the second picture above.
the following picture is tes folder, there's nothing in tes folder except 1.txt
You are calling File.Move() with a full path for your sourceFileName and a relative path for your destFileName. The relative file path is relative to the current working directory and not to the source file path. I expect that a stackoverflow file exists in the current working directory, most likely created the first time you ran this code.
your File.Move is changing them all to StackOverflow not using the prefix and suffix. If you only have one file in the directory it shouldn't be an issue. Are you sure there is only 1 file?
public static void Move(
string sourceFileName,
string destFileName
)
Looking at this answer might be the clue as you are specifying relative path for the destination file. To obtain the current working directory, see GetCurrentDirectory
The sourceFileName and destFileName arguments are permitted to specify
relative or absolute path information. Relative path information is
interpreted as relative to the current working directory.
You should change
File.Move(f.FullName,"stackoverflow");
to
string fileName = f.Name.Replace(f.Extenstion,string.Empty);
string newFileName = string.Format("{0}{1}{2}",prefix,fileName,suffix);
string newFileWithPath = Path.Combine(f.Directory,newFileName);
if (!File.Exists(newFileWithPath))
{
File.Move(f.FullName,newFileWithPath);
}
The code above will give you that error since, after the first run through, "stackoverflow" exists as a file. Make sure that you check if the destination file exists (using File.Exists) before calling File.Move.
Since your goal is renaming, I would suggest using a test folder filled with files rather than using a piecemeal approach. See if something like this helps:
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
f.MoveTo(#filepath + #"\" + prefix + f.Name.Insert(f.Name.LastIndexOf('.'),suffix));
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
on a side note using a listview to display the filenames and the changes before they're committed will help prevent unwanted changes.
I have found that using Path.GetFileName() in the code below works as I intend and gives me the name of the correct folder, but if I use Path.GetDirectoryName() it returns the name of the parent (UserGeneratedContent) folder instead. Why does this occur when both methods are passed the same path as a string? And why does Path.GetFileName() work on directories?
When I use Path.GetFileName() the text of the nodes in the Treeview are those of the folders it finds - this is what I want to happen, but if I use Path.GetDirectoryName() the text is the full path from #"UserGeneratedContent" on down for each node. Why does that happen?
And lastly, can my code be improved?
private void CheckForBaseFolder()
{
if (Directory.Exists(#"UserGeneratedContent"))
{
DirectoryInfo info = new DirectoryInfo(#"UserGeneratedContent");
DirectoryInfo[] subdirs = info.GetDirectories();
if (subdirs.Length != 0)
{
string path = Path.Combine(#"UserGeneratedContent", subdirs[0].ToString());
treeView1.Nodes.Add(CheckForSubFolders(path));
treeView1.SelectedNode = treeView1.Nodes[0];
}
else { MessageBox.Show("No User-Generated Folders Or Files Found"); }
}
else { Directory.CreateDirectory(#"UserGeneratedContent"); }
}
private TreeNode CheckForSubFolders(string path)
{
TreeNode folder = new TreeNode(path);
folder.Text = Path.GetFileName(path); // Works as intended, but.....
folder.Text = Path.GetDirectoryName(path); // Returns the parent folder
foreach(var subdirectory in Directory.GetDirectories(path))
{
folder.Nodes.Add(CheckForSubFolders(subdirectory));
}
folder.ImageIndex = 0;
folder.SelectedImageIndex = 1;
return folder;
}
Check your code, you are passing the path that doesn't contain filename but the last part of the path is directory UserGeneratedContent. Path.GetFileName returns the "The characters after the last directory character in path" so it retuns the last directory name instead of filename (you can make a file without extension). When you call Path.GetDirectoryName() on the same path string it returns "Directory information for path".
Check this code to see what I'm referring to:
Suppose you have directory "one" on C partition, and directory "two" in directory "one", and a file named "three.txt" in directory "two", when you execute this code it will produce:
string directory = Path.GetFileName(#"C:\one\two");
directory = Path.GetDirectoryName(#"C:\one\two");
directory will hold first "two" and then "C:\one"
string filename = Path.GetFileName(#"C:\one\two\three.txt");
directory = Path.GetDirectoryName(#"C:\one\two\three.txt");
but now, filename will hold "three.txt" and directory will hold "C:\one\two"
EDIT:This is later edit after the comments. I would modify the CheckForSubFolders method this way:
private TreeNode CheckForSubFolders(string path)
{
TreeNode folder = new TreeNode(path);
string dir = path.TrimEnd(new char[] { '\\' });
int index = dir.LastIndexOf('\\');
folder.Text = dir.Substring(index + 1);
//But I think that it is OK to use folder.Text = Path.GetFileName(path);
//since the filename of some file will never be passed to the CheckForSubFolders method
foreach(var subdirectory in Directory.GetDirectories(path))
{
folder.Nodes.Add(CheckForSubFolders(subdirectory));
}
folder.ImageIndex = 0;
folder.SelectedImageIndex = 1;
return folder;
}
Simply becasue as MSDN cliams for Path.GetDirectoryName:
In most cases, the string returned by this method consists of all
characters in the path up to but not including the last
DirectorySeparatorChar or AltDirectorySeparatorChar.
So if the parameter, is the path to directory itself, it just picks its parent directory, if any.
First of all how can you tell a difference from path that points to file from that which is pointing to a direcotry? Simply you cannot because you can create a file named file (does not contain a dot . and any extension) and you can create a folder that contains a dot folder.txt.
So how would you implement the logic that determines if path points to a file?
To answer your question methods GetFileName and GetDirectoryName simply assume that the last path part is a file name.