How to get files seperately to their extensions in MVC? - c#

I wrote a function that when user clicks on button for pdf, user will only show the pdf documents. I'm having a difficulty about where to put returns in this function.
public IActionResult GetFiles(string dir) {
if ((dir == null) || (!Directory.Exists(dir))) { return BadRequest(); }
var filesList = new List<FileImage>();
var pdffilesList = new List<FileImage>();
var dirInfo = new DirectoryInfo(dir);
var files = dirInfo.GetFiles();
foreach (var file in files)
{
if (file.Extension.Contains(".pdf"))
{
pdffilesList.Add(new FileImage
{
Name = file.Name,
FullName = Regex.Match(file.FullName, "wwwroot(.*)").Groups[1].Value,
LastWriteTime = file.LastWriteTime.ToString("yyyy.MM.dd HH:mm"),
DirectoryName = file.DirectoryName,
Length = file.Length,
Extension = file.Extension
});
return Ok(pdffilesList);
}
else
{
filesList.Add(new FileImage
{
Name = file.Name,
FullName = Regex.Match(file.FullName, "wwwroot(.*)").Groups[1].Value,
LastWriteTime = file.LastWriteTime.ToString("yyyy.MM.dd HH:mm"),
DirectoryName = file.DirectoryName,
Length = file.Length,
Extension = file.Extension
});
}
}
return Ok(pdffilesList);
}
What should I change in here ?

If you just want the PDF files, then don't do anything to include the others:
foreach (var file in files)
{
if (file.Extension.Contains(".pdf"))
{
pdffilesList.Add(new FileImage
{
Name = file.Name,
FullName = Regex.Match(file.FullName, "wwwroot(.*)").Groups[1].Value,
LastWriteTime = file.LastWriteTime.ToString("yyyy.MM.dd HH:mm"),
DirectoryName = file.DirectoryName,
Length = file.Length,
Extension = file.Extension
});
// note: removed this `return`
//return Ok(pdffilesList);
}
// It's not a .pdf, so ignore it
}
return Ok(pdffilesList);
You might also consider whether you really want Contains here. Do you want to include files with extensions like ".pdfqpz" or "foopdf"? Contains will give you any file whose extension contains the string "pdf" anywhere in it. You also will miss files that have extensions ".PDF" or ".pDf", etc. You probably want something like:
if (file.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase))

DirectoryInfo.GetFiles and EnumeratFiles can be used with a pattern. Instead of using separate branches you can use separate patterns:
var pattern=onlyPdfs? "*.pdf":"*";
var regex=new Regex("wwwroot(.*)");
var files=dirInfo.EnumerateFiles(pattern)
.Select(fi=>new FileImage
{
Name = file.Name,
FullName = regex.Match(file.FullName).Groups[1].Value,
LastWriteTime = file.LastWriteTime.ToString("yyyy.MM.dd HH:mm"),
DirectoryName = file.DirectoryName,
Length = file.Length,
Extension = file.Extension
});
return Ok(pdffilesList);
GetFiles waits until it finds all files and returns them in an array. EnumerateFiles on the other hand produces an IEnumerable<FileInfo> which returns each file as soon as it's found

Related

Action Result File - Filename when downloading is wrong in some cases

So this is the Code that returns the file. It is in a Method named GetMainReport.
var mBytes = MergePDF(formLanguage, mergedForms);
if (mBytes != null)
{
var cd = new System.Net.Mime.ContentDisposition
{
FileName = formLanguage.FileName,
Inline = formLanguage.FileExtension == FileExtension.PDF
};
Response.Headers.Add("content-disposition", cd.ToString());
AddDownloadedForm(formLanguage.Id);
return File(mBytes, type);
}
My Problem now is that if i go via this url:
http://localhost:8090/Library/105020.pdf
The filename when downloaded is 105020.pdf
if i use this one
http://localhost:8090/FormSearch/FormSearch/getMainReport?FormNumber=105020%20%20de
The filename is GetMainReport.pdf
any ideas why?
try this settings for ContentDisposition:
var cd = new System.Net.Mime.ContentDisposition
{
FileName = formLanguage.FileName,
DispositionType = DispositionTypeNames.Attachment,
Inline = formLanguage.FileExtension == FileExtension.PDF
};

Get files from a folder that I have created in Xamarin.Android

I want get all files from an external storage folder(wall_e_imgs)..Here are codes-
public void getImages()
{
var path1 = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.ToString();
string path = System.IO.Path.Combine(path1, "wall_e_imgs");
//var files= System.IO.Directory.GetFiles(Android.OS.Environment.ExternalStorageDirectory.ToString() + "wall_e_imgs");
//var files = System.IO.Directory.GetFiles(path);
//string path = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/wall_e_imgs";
//File directory=new File(path);
Java.IO.File directory = new Java.IO.File(path);
Java.IO.File[] files = directory.ListFiles();//always count is 0 even though there are lot files there
foreach (var i in files)
{
FileInfo info = new FileInfo(i.Name);
if (info.Name.Contains("Wall_e"))
{
di.Add(new DownloadedImages { Path1 = info.DirectoryName, Name1 = info.FullName });
}
}
}
But it always give 0 files even though there are lot of files.
Try this
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "yourfoldername";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var filesList = Directory.GetFiles(folder);
foreach (var file in filesList)
{
var filename = Path.GetFileName(file);
}
Try something like this:
// Use whatever folder path you want here, the special folder is just an example
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "wall_e_imgs");
if (Directory.Exists(folderPath))
{
var files = Directory.EnumerateFiles(folderPath);
foreach (var file in files)
{
// Do your stuff
}
}
Please note that this uses the Directory class from System.IO, not Java.IO
ffilelist will contain a list of mp3 files in "/storage/emulated/0/Music/"
string phyle;
string ffilelist = "";
public void listfiles()
{
try
{
var path1 = "/storage/emulated/0/Music/";
var mp3Files = Directory.EnumerateFiles(path1, "*.mp3", SearchOption.AllDirectories);
foreach (string currentFile in mp3Files)
{
phyle = currentFile;
ffilelist = ffilelist + "\n" + phyle;
}
//playpath(phyle); // play the last file found
}
catch (Exception e9)
{
Toast.MakeText(ApplicationContext, "ut oh\n"+e9.Message , ToastLength.Long).Show();
}
}

retrieving a matched name video in MediaElement control WPF

i want to play the video which name is entered in text box. But it does not play the exact video it plays the first video present in folder. any help please..
Code
String vid_name = data.Text;
string complete_name = vid_name.ToLower() + ".mp4";
string root = System.IO.Path.GetDirectoryName("D:/abc");
string[] supportedExtensions = new[] { ".mp4" };
var files = Directory.GetFiles(Path.Combine(root, "Videos"), "*.*").Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower()));
List<VideosDetail> videos = new List<VideosDetail>();
VideosDetail id;
foreach (var file in files)
{
id = new VideosDetail()
{
Path = file,
FileName = Path.GetFileName(file),
Extension = Path.GetExtension(file)
};
FileInfo fi = new FileInfo(file);
id.FileName = fi.Name;
id.Size = fi.Length;
videos.Add(id);
if (id.FileName == complete_name)
{
VideoList.ItemsSource = videos; //**Problem comes here
}
else
{
MessageBox.Show("no such video is available. ");
}
}
Since videos is a List, the line
VideoList.ItemsSource = videos;
Points to all the videos in the folder (up to the one that actually matches the filename you entered). Hence, the unwanted result.
You should probably pass the index of the video in your list, something like:
player.Source = videos[x];
Hope this helps!

C# return full path with GetFiles

Use this code for search files in directory:
FileInfo[] files = null;
string path = some_path;
DirectoryInfo folder = new DirectoryInfo(path);
files = folder.GetFiles("*.*", SearchOption.AllDirectories);
This return only filename and extension (text.exe). How to return full path to file(C:\bla\bla\bla\text.exe)?
If I use Directory.GetFiles("*.*"), this return full path. But if folder contains point in name(C:\bla\bla\test.0.1), result contains path to folder without file:
0 C:\bla\bla\bla\text.exe
1 C:\bla\bla\test.0.1
2 C:\bla\text.exe
etc.
FileInfo contains a FullName property, which you can use to retrieve full path to a file
var fullNames = files.Select(file => file.FullName).ToArray();
Check
This code on my machine:
FileInfo[] files = null;
string path = #"C:\temp";
DirectoryInfo folder = new DirectoryInfo(path);
files = folder.GetFiles("*.*", SearchOption.AllDirectories);
//you need string from FileInfo to denote full path
IEnumerable<string> fullNames = files.Select(file => file.FullName);
Console.WriteLine ( string.Join(Environment.NewLine, fullNames ) );
prints
C:\temp\1.dot
C:\temp\1.jpg
C:\temp\1.png
C:\temp\1.txt
C:\temp\2.png
C:\temp\a.xml
...
Full solution
The solution to your problem might look like this:
string path = #"C:\temp";
DirectoryInfo folder = new DirectoryInfo(path);
var directories = folder.GetDirectories("*.*", SearchOption.AllDirectories);
IEnumerable<string> directoriesWithDot =
directories.Where(dir => dir.Name.Contains("."))
.Select(dir => dir.FullName);
IEnumerable<string> filesInDirectoriesWithoutDot =
directories.Where(dir => !dir.Name.Contains("."))
.SelectMany(dir => dir.GetFiles("*.*", SearchOption.TopDirectoryOnly))
.Select(file => file.FullName);
Console.WriteLine ( string.Join(Environment.NewLine, directoriesWithDot.Union(filesInDirectoriesWithoutDot) ) );
Each FileInfo object has a FullName property.
But if folder contains point in name (C:\bla\bla\test.0.1), result contains path to folder without file
This is an entirely different issue with possibly diffeent answers/workarounds. Can you be more specific?
I cannot reproduce this.
You need to use FileInfo.
Directory.GetFiles("", SearchOption.AllDirectories).Select(file => new FileInfo(file).FullName);
public static IEnumerable<string> GetAllFilesRecursively(string inputFolder)
{
var queue = new Queue<string>();
queue.Enqueue(inputFolder);
while (queue.Count > 0)
{
inputFolder = queue.Dequeue();
try
{
foreach (string subDir in Directory.GetDirectories(inputFolder))
{
queue.Enqueue(subDir);
}
}
catch (Exception ex)
{
Console.Error.WriteLine("GetAllFilesRecursively: " + ex);
}
string[] files = null;
try
{
files = Directory.GetFiles(inputFolder);
}
catch (Exception ex)
{
Console.Error.WriteLine("GetAllFilesRecursively: " + ex);
}
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
yield return files[i];
}
}
}
}
you can try this :
void GetFiles()
{
DirectoryInfo d= new DirectoryInfo(strFolderPath);
//file extension for pdf
var files = d.GetFiles("*.pdf*");
FileInfo[] subfileInfo = files.ToArray<FileInfo>();
if (subfileInfo.Length > 0)
{
for (int j = 0; j < subfileInfo.Length; j++)
{
bool isHidden = ((File.GetAttributes(subfileInfo[j].FullName) & FileAttributes.Hidden) == FileAttributes.Hidden);
if (!isHidden)
{
string strExtention = th.GetExtension(subfileInfo[j].FullName);
if (strExtention.Contains("pdf"))
{
string path = subfileInfo[j].FullName;
string name = bfileInfo[j].Name;
}
}
}
}
You can use FileSystemInfo.FullName property.
Gets the full path of the directory or file.

C#:Getting all image files in folder

I am trying to get all images from folder but ,this folder also include sub folders. like /photos/person1/ and /photos/person2/ .I can get photos in folder like
path= System.IO.Directory.GetCurrentDirectory() + "/photo/" + groupNO + "/";
public List<String> GetImagesPath(String folderName)
{
DirectoryInfo Folder;
FileInfo[] Images;
Folder = new DirectoryInfo(folderName);
Images = Folder.GetFiles();
List<String> imagesList = new List<String>();
for (int i = 0; i < Images.Length; i++)
{
imagesList.Add(String.Format(#"{0}/{1}", folderName, Images[i].Name));
// Console.WriteLine(String.Format(#"{0}/{1}", folderName, Images[i].Name));
}
return imagesList;
}
But how can I get all photos in all sub folders? I mean I want to get all photos in /photo/ directory at once.
Have a look at the DirectoryInfo.GetFiles overload that takes a SearchOption argument and pass SearchOption.AllDirectories to get the files including all sub-directories.
Another option is to use Directory.GetFiles which has an overload that takes a SearchOption argument as well:
return Directory.GetFiles(folderName, "*.*", SearchOption.AllDirectories)
.ToList();
I'm using GetFiles wrapped in method like below:
public static String[] GetFilesFrom(String searchFolder, String[] filters, bool isRecursive)
{
List<String> filesFound = new List<String>();
var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
foreach (var filter in filters)
{
filesFound.AddRange(Directory.GetFiles(searchFolder, String.Format("*.{0}", filter), searchOption));
}
return filesFound.ToArray();
}
It's easy to use:
String searchFolder = #"C:\MyFolderWithImages";
var filters = new String[] { "jpg", "jpeg", "png", "gif", "tiff", "bmp", "svg" };
var files = GetFilesFrom(searchFolder, filters, false);
There's a good one-liner solution for this on a similar thread:
get all files recursively then filter file extensions with LINQ
Or if LINQ cannot be used, then use a RegEx to filter file extensions:
var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories);
List<string> imageFiles = new List<string>();
foreach (string filename in files)
{
if (Regex.IsMatch(filename, #"\.jpg$|\.png$|\.gif$"))
imageFiles.Add(filename);
}
I found the solution this Might work
foreach (string img in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"*.bmp" + "*.jpg" + "SO ON"))
You need the recursive form of GetFiles:
DirectoryInfo.GetFiles(pattern, searchOption);
(specify AllDirectories as the SearchOption)
Here's a link for more information:
MSDN: DirectoryInfo.GetFiles
This allows you to use use the same syntax and functionality as Directory.GetFiles(path, pattern, options); except with an array of patterns instead of just one.
So you can also use it to do tasks like find all files that contain the word "taxes" that you may have used to keep records over the past year (xlsx, xls, odf, csv, tsv, doc, docx, pdf, txt...).
public static class CustomDirectoryTools {
public static string[] GetFiles(string path, string[] patterns = null, SearchOption options = SearchOption.TopDirectoryOnly) {
if(patterns == null || patterns.Length == 0)
return Directory.GetFiles(path, "*", options);
if(patterns.Length == 1)
return Directory.GetFiles(path, patterns[0], options);
return patterns.SelectMany(pattern => Directory.GetFiles(path, pattern, options)).Distinct().ToArray();
}
}
In order to get all image files on your c drive you would implement it like this.
string path = #"C:\";
string[] patterns = new[] {"*.jpg", "*.jpeg", "*.jpe", "*.jif", "*.jfif", "*.jfi", "*.webp", "*.gif", "*.png", "*.apng", "*.bmp", "*.dib", "*.tiff", "*.tif", "*.svg", "*.svgz", "*.ico", "*.xbm"};
string[] images = CustomDirectoryTools.GetFiles(path, patterns, SearchOption.AllDirectories);
You can use GetFiles
GetFiles("*.jpg", SearchOption.AllDirectories)
GetFiles("*.jpg", SearchOption.AllDirectories) has a problem at windows7. If you set the directory to c:\users\user\documents\, then it has an exception: because of windows xp, win7 has links like Music and Pictures in the Documents folder, but theese folders don't really exists, so it creates an exception. Better to use a recursive way with try..catch.
This will get list of all images from folder and sub folders and it also take care for long file name exception in windows.
// To handle long folder names Pri external library is used.
// Source https://github.com/peteraritchie/LongPath
using Directory = Pri.LongPath.Directory;
using DirectoryInfo = Pri.LongPath.DirectoryInfo;
using File = Pri.LongPath.File;
using FileInfo = Pri.LongPath.FileInfo;
using Path = Pri.LongPath.Path;
// Directory and sub directory search function
public void DirectoryTree(DirectoryInfo dr, string searchname)
{
FileInfo[] files = null;
var allFiles = new List<FileInfo>();
try
{
files = dr.GetFiles(searchname);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
if (files != null)
{
try
{
foreach (FileInfo fi in files)
{
allFiles.Add(fi);
string fileName = fi.DirectoryName + "\\" + fi.Name;
string orgFile = fileName;
}
var subDirs = dr.GetDirectories();
foreach (DirectoryInfo di in subDirs)
{
DirectoryTree(di, searchname);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public List<String> GetImagesPath(String folderName)
{
var dr = new DirectoryInfo(folderName);
string ImagesExtensions = "jpg,jpeg,jpe,jfif,png,gif,bmp,dib,tif,tiff";
string[] imageValues = ImagesExtensions.Split(',');
List<String> imagesList = new List<String>();
foreach (var type in imageValues)
{
if (!string.IsNullOrEmpty(type.Trim()))
{
DirectoryTree(dr, "*." + type.Trim());
// output to list
imagesList.Add = DirectoryTree(dr, "*." + type.Trim());
}
}
return imagesList;
}
var files = new DirectoryInfo(path).GetFiles("File")
.OrderByDescending(f => f.LastWriteTime).First();
This could gives you the perfect result of searching file with its latest mod

Categories