how to find file's path according to filename? - c#

i have filename according to this file name. i need to find file's path.
how to find file's path according to filename? i need to find file's path according to file name sample code:
string path= System.IO.Directory.GetDirectories(#"c:\", "kategori",System.IO.SearchOption.AllDirectories).First();
But i need :
string path= System.IO.Directory.GetDirectories(#"anyFolder", "kategori",System.IO.SearchOption.AllDirectories).First();
i need below
Main()
{
string path = PathFinder("Afilename")
}
output: C:\myFiles\AfileName
string PathFinder(string fileName)
{
..................
.................
........
.......
....
..
.
}

Probably a function like this could work for you:
public static String SearchFileRecursive(String baseFolderPath, String fileName)
{
// Returns, if found, the full path of the file; otherwise returns null.
var response = Path.Combine(baseFolderPath, fileName);
if (File.Exists(response))
{
return response;
}
// Recursion.
var directories = Directory.GetDirectories(baseFolderPath);
for (var i = 0; i < directories.Length; i++)
{
response = SearchFileRecursive(directories[i], fileName);
if (response != null) return response;
}
// { file was not found }
return null;
}

http://support.microsoft.com/kb/303974

I'd like more the LINQish way:
public static IEnumerable<FileInfo> FindFile(string fileName)
{
if (String.IsNullOrEmpty(fileName))
throw new ArgumentException("fileName");
return Directory.GetLogicalDrives()
.SelectMany(drive => FindFile(fileName, drive));
}
public static IEnumerable<FileInfo> FindFile(string fileName, string folderName)
{
if (String.IsNullOrEmpty(fileName))
throw new ArgumentException("fileName");
if (String.IsNullOrEmpty(fileName))
throw new ArgumentException("folderName");
var matchingFiles = Directory.EnumerateFiles(folderName)
.Where(file => Path.GetFileName(file) == fileName)
.Select(file => new FileInfo(file));
var matchingFilesFromSubDirs = Directory.EnumerateDirectories(folderName)
.SelectMany(directory => FindFile(fileName, directory));
return matchingFiles.Concat(matchingFilesFromSubDirs);
}
which can be used by:
foreach (var file in FindFile("myFile.ext"))
{
Console.WriteLine("Name: " + file.FullName);
}

Related

How to get the list of files with specific extension in Xamarin Android?

I need suggestion on getting a list of PDF files from the external storage in android device
1.You could traverse the folder and filter the PDF files:
public void Search_Pdf_Dir(File dir)
{
string pdfPattern = ".pdf";
File[] FileList = dir.ListFiles();
if (FileList != null)
{
for (int i = 0; i < FileList.Length; i++)
{
if (FileList[i].IsDirectory)
{
Search_Pdf_Dir(FileList[i]);
}
else
{
if (FileList[i].Name.EndsWith(pdfPattern))
{
//here you have that file.
}
}
}
}
}
then you could call like Search_Pdf_Dir(Android.OS.Environment.ExternalStorageDirectory);
2.use MediaStore - Uri to query all types of files :
ContentResolver cr = ContentResolver;
Android.Net.Uri uri = MediaStore.Files.GetContentUri("external");
// every column, although that is huge waste, you probably need
// BaseColumns.DATA (the path) only.
string[] projection = null;
string selectionMimeType = MediaStore.Files.FileColumns.MediaType + "=?";
string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension("pdf");
string[] selectionArgsPdf = new string[] { mimeType };
string sortOrder = null;
var allPdfFiles = cr.Query(uri, projection, selectionMimeType, selectionArgsPdf, sortOrder);
while (allPdfFiles.MoveToNext())
{
int column_index = allPdfFiles.GetColumnIndexOrThrow(MediaStore.Images.Media.InterfaceConsts.Data);
string filePath = allPdfFiles.GetString(column_index);//the pdf path
}

How to get the extension from ContentDisposition [duplicate]

How do I get Content-Disposition parameters I returned from WebAPI controller using WebClient?
WebApi Controller
[Route("api/mycontroller/GetFile/{fileId}")]
public HttpResponseMessage GetFile(int fileId)
{
try
{
var file = GetSomeFile(fileId)
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(file));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = file.FileOriginalName;
/********* Parameter *************/
response.Content.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("MyParameter", "MyValue"));
return response;
}
catch(Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
}
Client
void DownloadFile()
{
WebClient wc = new WebClient();
wc.DownloadDataCompleted += wc_DownloadDataCompleted;
wc.DownloadDataAsync(new Uri("api/mycontroller/GetFile/18"));
}
void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
WebClient wc=sender as WebClient;
// Try to extract the filename from the Content-Disposition header
if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
{
string fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 10).Replace("\"", ""); //FileName ok
/****** How do I get "MyParameter"? **********/
}
var data = e.Result; //File OK
}
I'm returning a file from WebApi controller, I'm attaching the file name in the response content headers, but also I'd like to return an aditional value.
In the client I'm able to get the filename, but how do I get the aditional parameter?
If you are working with .NET 4.5 or later, consider using the System.Net.Mime.ContentDisposition class:
string cpString = wc.ResponseHeaders["Content-Disposition"];
ContentDisposition contentDisposition = new ContentDisposition(cpString);
string filename = contentDisposition.FileName;
StringDictionary parameters = contentDisposition.Parameters;
// You have got parameters now
Edit:
otherwise, you need to parse Content-Disposition header according to it's specification.
Here is a simple class that performs the parsing, close to the specification:
class ContentDisposition {
private static readonly Regex regex = new Regex(
"^([^;]+);(?:\\s*([^=]+)=((?<q>\"?)[^\"]*\\k<q>);?)*$",
RegexOptions.Compiled
);
private readonly string fileName;
private readonly StringDictionary parameters;
private readonly string type;
public ContentDisposition(string s) {
if (string.IsNullOrEmpty(s)) {
throw new ArgumentNullException("s");
}
Match match = regex.Match(s);
if (!match.Success) {
throw new FormatException("input is not a valid content-disposition string.");
}
var typeGroup = match.Groups[1];
var nameGroup = match.Groups[2];
var valueGroup = match.Groups[3];
int groupCount = match.Groups.Count;
int paramCount = nameGroup.Captures.Count;
this.type = typeGroup.Value;
this.parameters = new StringDictionary();
for (int i = 0; i < paramCount; i++ ) {
string name = nameGroup.Captures[i].Value;
string value = valueGroup.Captures[i].Value;
if (name.Equals("filename", StringComparison.InvariantCultureIgnoreCase)) {
this.fileName = value;
}
else {
this.parameters.Add(name, value);
}
}
}
public string FileName {
get {
return this.fileName;
}
}
public StringDictionary Parameters {
get {
return this.parameters;
}
}
public string Type {
get {
return this.type;
}
}
}
Then you can use it in this way:
static void Main() {
string text = "attachment; filename=\"fname.ext\"; param1=\"A\"; param2=\"A\";";
var cp = new ContentDisposition(text);
Console.WriteLine("FileName:" + cp.FileName);
foreach (DictionaryEntry param in cp.Parameters) {
Console.WriteLine("{0} = {1}", param.Key, param.Value);
}
}
// Output:
// FileName:"fname.ext"
// param1 = "A"
// param2 = "A"
The only thing that should be considered when using this class is it does not handle parameters (or filename) without a double quotation.
Edit 2:
It can now handle file names without quotations.
You can parse out the content disposition using the following framework code:
var content = "attachment; filename=myfile.csv";
var disposition = ContentDispositionHeaderValue.Parse(content);
Then just take the pieces off of the disposition instance.
disposition.FileName
disposition.DispositionType
With .NET Core 3.1 and more the most simple solution is:
using var response = await Client.SendAsync(request);
response.Content.Headers.ContentDisposition.FileName
The value is there I just needed to extract it:
The Content-Disposition header is returned like this:
Content-Disposition = attachment; filename="C:\team.jpg"; MyParameter=MyValue
So I just used some string manipulation to get the values:
void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
WebClient wc=sender as WebClient;
// Try to extract the filename from the Content-Disposition header
if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
{
string[] values = wc.ResponseHeaders["Content-Disposition"].Split(';');
string fileName = values.Single(v => v.Contains("filename"))
.Replace("filename=","")
.Replace("\"","");
/********** HERE IS THE PARAMETER ********/
string myParameter = values.Single(v => v.Contains("MyParameter"))
.Replace("MyParameter=", "")
.Replace("\"", "");
}
var data = e.Result; //File ok
}
As #Mehrzad Chehraz said you can use the new ContentDisposition class.
using System.Net.Mime;
// file1 is a HttpResponseMessage
FileName = new ContentDisposition(file1.Content.Headers.ContentDisposition.ToString()).FileName

How to read path from another method

I have a method which unzips file from my method, and I have a separate method which I want to create so it can read the unzip files and load them as needed.
private string UnzipFiles()
{
Chilkat.Zip zip = new Chilkat.Zip();
string zippedFilePath = #"C:\Users\TestData";
string unzippedFilePath = #"C:\Users\Temp";
bool success = zip.UnlockComponent("LIVECOZIP_3BzssvnbmYxp");
if (!success)
{
string errorMsg = zip.LastErrorText;
Console.WriteLine(errorMsg);
return errorMsg;
}
string[] newzip = (Directory.GetFiles(zippedFilePath));
foreach (string file in newzip)
{
success = zip.OpenZip(file);
{
Console.WriteLine(zip.LastErrorText);
}
zip.DecryptPassword = "hANhvU8MX7iq0f2M";
int unzipCount;
unzipCount = zip.Unzip(unzippedFilePath);
if (unzipCount < 0)
{
Console.WriteLine("unzipping file");
}
}
return unzippedFilePath;
The method below is where I need help. I want to call the method above and be able to read each file. Right now I am getting error.
public void LoadNewFile()
{
UnzipFiles();
foreach (String file in UnzipFiles)
//How to call each file?
{
userSelectedFilePath += file + Environment.NewLine;
names_of_files.Add(file);
}
Try this:
var path = UnzipFiles();
var unZippedFiles = Directory.GetFiles(path);
foreach (var file in unZippedFiles)
{
//tratata
}
I would say you need to change UnzipFiles to return a List of strings. Something like this:
private List<string> UnzipFiles()
{
Chilkat.Zip zip = new Chilkat.Zip();
string zippedFilePath = #"C:\Users\TestData";
string unzippedFilePath = #"C:\Users\Temp";
var unzippedFileList = new List<string>();
bool success = zip.UnlockComponent("LIVECOZIP_3BzssvnbmYxp");
if (!success)
{
string errorMsg = zip.LastErrorText;
Console.WriteLine(errorMsg);
return errorMsg;
}
string[] newzip = (Directory.GetFiles(zippedFilePath));
foreach (string file in newzip)
{
unzippedFileList.Add(file);
success = zip.OpenZip(file);
{
Console.WriteLine(zip.LastErrorText);
}
zip.DecryptPassword = "hANhvU8MX7iq0f2M";
int unzipCount;
unzipCount = zip.Unzip(unzippedFilePath);
if (unzipCount < 0)
{
Console.WriteLine("unzipping file");
}
}
return unzippedFileList;
}

C#: Get first directory name of a relative path

How to get the first directory name in a relative path, given that they can be different accepted directory separators?
For example:
foo\bar\abc.txt -> foo
bar/foo/foobar -> bar
Works with both forward and back slash
static string GetRootFolder(string path)
{
while (true)
{
string temp = Path.GetDirectoryName(path);
if (String.IsNullOrEmpty(temp))
break;
path = temp;
}
return path;
}
Seems like you could just use the string.Split() method on the string, then grab the first element.
example (untested):
string str = "foo\bar\abc.txt";
string str2 = "bar/foo/foobar";
string[] items = str.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(items[0]); // prints "foo"
items = str2.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(items[0]); // prints "bar"
The most robust solution would be to use DirectoryInfo and FileInfo. On a Windows NT-based system it should accept either forward or backslashes for separators.
using System;
using System.IO;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(GetTopRelativeFolderName(#"foo\bar\abc.txt")); // prints 'foo'
Console.WriteLine(GetTopRelativeFolderName("bar/foo/foobar")); // prints 'bar'
Console.WriteLine(GetTopRelativeFolderName("C:/full/rooted/path")); // ** throws
}
private static string GetTopRelativeFolderName(string relativePath)
{
if (Path.IsPathRooted(relativePath))
{
throw new ArgumentException("Path is not relative.", "relativePath");
}
FileInfo fileInfo = new FileInfo(relativePath);
DirectoryInfo workingDirectoryInfo = new DirectoryInfo(".");
string topRelativeFolderName = string.Empty;
DirectoryInfo current = fileInfo.Directory;
bool found = false;
while (!found)
{
if (current.FullName == workingDirectoryInfo.FullName)
{
found = true;
}
else
{
topRelativeFolderName = current.Name;
current = current.Parent;
}
}
return topRelativeFolderName;
}
}
Based on the answer provided by Hasan Khan ...
private static string GetRootFolder(string path)
{
var root = Path.GetPathRoot(path);
while (true)
{
var temp = Path.GetDirectoryName(path);
if (temp != null && temp.Equals(root))
break;
path = temp;
}
return path;
}
This will give the the top level folder
Based on the question you ask, the following should work:
public string GetTopLevelDir(string filePath)
{
string temp = Path.GetDirectoryName(filePath);
if(temp.Contains("\\"))
{
temp = temp.Substring(0, temp.IndexOf("\\"));
}
else if (temp.Contains("//"))
{
temp = temp.Substring(0, temp.IndexOf("\\"));
}
return temp;
}
When passed foo\bar\abc.txt it will foo as wanted- same for the / case
Here is another example in case your path if following format:
string path = "c:\foo\bar\abc.txt"; // or c:/foo/bar/abc.txt
string root = Path.GetPathRoot(path); // root == c:\
This should work fine
string str = "foo\bar\abc.txt";
string str2 = "bar/foo/foobar";
str.Replace("/", "\\").Split('\\').First(); // foo
str2.Replace("/", "\\").Split('\\').First(); // bar
Here my example, with no memory footprint (without creating new strings in memory):
var slashIndex = relativePath.IndexOf('/');
var backslashIndex = relativePath.IndexOf('\\');
var firstSlashIndex = (slashIndex > 0) ? (slashIndex < backslashIndex ? slashIndex : (backslashIndex == -1) ? slashIndex : backslashIndex) : backslashIndex;
var rootDirectory = relativePath.Substring(0, firstSlashIndex);

C# how to check if file is in folder according to object of filenames

I have the following method:
public static Boolean CheckContents(string ExportDirectory, string FileName, string DspFleName, String RteFleName, string FulRteName, string EqpFleName, int CompanyId, string CompanyName)
{
if (DspFleName != "None")
{
IList<string> DspFle= DspFleName.Split(',');
IList<string> ActualFiles = Directory.GetFiles(ExportDirectory);
for (int i = 0; i < DspFle.Count; i++)
{
if (DspFle[i] != ActualFiles[i])
{
return false;
}
}
}
return true;
}
}
Basically what this code is meant to do is get all file names from the DspFle field which is seperated by a ,. So this would look like so:
test.txt,test2.csv
Then it is getting the acutal files in the directory that is specified from 'ExportDirectory' and returns those into an IList
I am having 2 problems here:
1.The Directory.GetFiles returns the whole file path so that will always return false. I also tried Path.GetFileNames and this only returns the file name but it does not return the extension.
2.I need to compare my entire DspFle to my ActualFile IList as the file names could be in different parts of the list.
Any ideas?
Your code expects not only for the file to exist, but to be in the same position...
Try this one instead :
public static Boolean CheckContents(string ExportDirectory, string DspFleName)
{
if (DspFleName == "None")
return true;
var DspFle = DspFleName.Split(',');
var ActualFiles = Directory.GetFiles(ExportDirectory);
foreach(var file in DspFle)
if (!ActualFiles.Any(x=>Path.GetFileName(x).Equals(file)))
return false;
return true;
}
List<String> fileNames = new List<String>();
String[] files = Directory.GetFiles(".");
foreach (String file in files)
{
fileNames.Add(System.IO.Path.GetFileName(file));
}
That will return the filename with extensions. You can then compare to your IList at that point.
Why bother going through all the trouble of building two lists when you could just check if each file exists in the directory? Effectively that is what your code is doing anyway.
foreach(string DspFle in DspFleName.Split(',')) {
string CheckPath = Path.Combine(ExportDirectory,DspFle[i]);
if (!File.Exists(CheckPath)) return false;
}
return true;
Maybe this is will do what you want?
if (DspFle == "None")
return true;
List<string> DspFle = DspFleName.Split(',');
List<string> ActualFiles = new List<string>();
foreach (string file in Directory.GetFiles(ExportDirectory)
{
DirectoryInfo di = new DirectoryInfo(file);
ActualFiles.Add(di.Name);
}
foreach (string file in DspFle)
{
if (!ActualFiles.Contains(dspFile))
return false;
}
return true;
DirectoryInfo will allow you to return the name of a file including the extension.

Categories

Resources