Get file path and file name from directory - C# - c#

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)

Related

not able to get correct file path for subfolder file

in this I am trying to load all the excel data from specified folderpath and its subfolder present inside it to sql server... Problem is I am able to read the main folder and subfolder, but while taking the data from sub folder file it taking the path of main folder for that sub folder file
example: file path - d:\test
sub directory : d:\test\test2
inside subdirectory my file is present but when iterating it is reading the path of sub directory file as : d:\test\file_name
please help in this
```DirectoryInfo directory = new DirectoryInfo(#FolderPath);
FileInfo[] files = directory.GetFiles("*.xlsx", SearchOption.AllDirectories);```
// Directory structure:
// C:\Temp\ExcelFiles\Excel1.xlsx
// C:\Temp\ExcelFiles\SubFolder\Excel2.xlsx
var path = #"C:\Temp\ExcelFiles";
var allExcelFilesInPathAndSubFolders = Directory.GetFiles(path, "*.xlsx", SearchOption.AllDirectories);
This approach returns the expected 2 Excel file names as string array (i.e. C:\Temp\ExcelFiles\Excel1.xlsx and C:\Temp\ExcelFiles\SubFolder\Excel2.xlsx).
The approach in your post returns an array of FileInfo. You can get all relevant information from that; the name with or without path, the file extension, and using Path.GetFileNameWithoutExtension you can get the name without extension.
// Directory structure:
// C:\Temp\ExcelFiles\Excel1.xlsx
// C:\Temp\ExcelFiles\SubFolder\Excel2.xlsx
var path = #"C:\Temp\ExcelFiles";
DirectoryInfo directory = new DirectoryInfo(path);
FileInfo[] files = directory.GetFiles("*.xlsx", SearchOption.AllDirectories);
// Excel1.xlsx
var firstFileName = files.First().Name;
// Excel1
var firstFileNameWithoutExtension = Path.GetFileNameWithoutExtension(files.First().Name);
// .xlsx
var fileFileExtension = files.First().Extension;
// C:\Temp\ExcelFiles\Excel1.xlsx
var firstFileFullName = files.First().FullName;

Create Directory will multiple names passed by parameter C#

I have to create multiple folders as e.g.
Directory.CreateDirectory("PATH\\" + _year + "filetosave.txt");
while "PATH\\" is the full path where the folder will reside, _year is the parameter and "filetosave.txt" is the file which is to be saved in respective folder.
And at run time, it should create respective folders with years in the folder name containing respective files to save.
Whereas .CreateDirectory() method only accepts string path or string path, security access as parameters.
How will we create these parameterized folders?
How can we make a check that a specified directory already exists or not?
var path = Path.Combine("PATH\\", _year.ToString(), "filettosave.txt");
Directory.CreateDirectory(path);
Directory.CreateDirectory
Creates all directories and subdirectories in the specified path unless they already exist.
Emphasis mine.
As commented, use Path.Combine when trying to build system paths:
var root = "Path";
var year = "2016";
var filename = "filetosave.txt";
var path = Path.Combine(root, year, filename);
// path = Path\2016\filetosave.txt
Directory.CreateDirectory(path);
In general, use System.IO.Path.Combine to build paths. It simplifies this task.
string dir = System.IO.Path.Combine(rootPath, _year.ToString());
Directory.CreateDirectory(dir);
string file = System.IO.Path.Combine(dir, "filetosave.txt");
FileStream fs = File.Create(file)

GetFiles with spaces in filename

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.

The directory name is invalid

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)

Issue in File path

In my project there is a folder and in that folder there is text file. I want to read that text file
string FORM_Path = #"C:\Users\...\Desktop\FormData\Login.txt";
bool first = true;
string line;
try
{
using (StreamReader streamReader = File.OpenText(FORM_Path))
{
line = streamReader.ReadLine();
}
}
but I always get an error - file does not exist. how can i solve the problem in the path of text file.
Make sure your file's properties are set to copy the file to output directory. Then you can use the following line to get full path of your text file:
string FilePath = System.IO.Path.Combine(Application.StartupPath, "FormData\Login.txt");
You path is not in correct format. Use #".\FormData\Login.txt" instead of what you have
You are trying to give relative path instead of physical path. If you can use asp.net use Server.MapPath
string FORM_Path = Server.MapPath("~/FormData/Login.txt");
If the text file is in execution folder then you can use AppDomain.BaseDirectory
string FORM_Path = AppDomain.CurrentDomain.BaseDirectory + "FormData\\Login.txt";
If it is not possible to use some base path then you can give complete path.
Avoid using relative paths. Instead consider using the methods in the Path class.
Path.Combine
Path.GetDirectoryName
Step 1: get absolute path of the executable
var path = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
Step 2: get the working dir
var dir = Path.GetDirectoryName(path);
Step 3: build the new path
var filePath = Path.Combine(dir , #"FormData\Login.txt");

Categories

Resources