Displaying desired files only in asp.net - c#

DirectoryInfo Dir = new DirectoryInfo(Server.MapPath(strheadlinesid));
FileInfo[] FileList = Dir.GetFiles("*.txt", SearchOption.AllDirectories);
In the Place of *.txt ,I want to mention some more file extensions how can I do that.
I used another type of approach but I have a small problem in it when I use the FI as hyperlink it's giving total path.but I want to print only the file name not fullpath.
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.emf,*.xbm,*.ico,*.eps,*.tif,*.tiff,*.g01,*.g02,*.g03,*.g04,*.g05,*.g06,*.g07,*.g08";
foreach (string FI in Directory.GetFiles(Server.MapPath(strheadlinesid), "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
Response.Write("<td><a href= view5.aspx?file=" + strheadlinesid + "\\" + FI + " target=_self;> " +
FI + "</a></td>");
}

Try
string fileFilter = "*.wma,*.jpeg,*.txt";
string[] fileExt = fileFilter.Split(',');
FileInfo[] fileInfo = null;
DirectoryInfo dir = new DirectoryInfo("D:\\Test");
List<FileInfo[]> listFileInfo = new List<FileInfo[]>();
foreach (string strVar in fileExt)
{
fileInfo = dir.GetFiles(strVar, SearchOption.AllDirectories);
listFileInfo.Add(fileInfo);
}

Related

How can i get files specific files names from directory?

string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry, "*.jpg");
But not only gif i want to specify that also it will be only files that contains the name infrared. For example i have files name 0infrared.gif and also 0visible.gif and i want to get all the files that are infrared.
This will get you all files with infrared in file name and with extension jpg
string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry,
"*infrared*.jpg");
string[] list = Directory.GetFiles(
countriesMainPath + "\\" + currentDownloadCountry,
"*infrared*.*");
This will return all the files contain infrared in their file name.
I think this may be what you look for. ref: MSDN
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
{
string[] searchPatterns = searchPattern.Split('|');
List<string> files = new List<string>();
foreach (string sp in searchPatterns)
files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption));
files.Sort();
return files.ToArray();
}
Usage
var wantedImgs = GetFiles(
dirYouWant, "*infrared*.jpg|*infrared*.gif",
earchOption.TopDirectoryOnly);
string partialName = "infrared";
DirectoryInfo dir = new DirectoryInfo(#"c:\");
FileInfo[] filesInDir = dir.GetFiles("*" + partialName + "*.*");
foreach (FileInfo foundFile in filesInDir)
{
string fullName = foundFile.FullName;
Console.WriteLine(fullName);
}
maybe *infrared*.(jpg|gif) will work

Move files to folder but ignore certain ones

I'm trying to move text files into a folder but ignore test.txt and all others will be moved to FileHolder folder. When I run it it still moves all the txt files to the folder.
private void testmodule()
{
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);
List<String> AllDeskTopFiles = Directory.GetFiles(filepath, "*.txt*").ToList();
foreach (string file in AllDeskTopFiles)
{
if (file != "test.txt")
{
FileInfo mFile = new FileInfo(file);
if (new FileInfo(d + "\\FileHolder\\" + mFile.Name).Exists == false)
mFile.MoveTo(d + "\\FileHolder\\" + mFile.Name);
}
}
}
Your file variable contains the full path.
You need to filter based on the file name, not the full path.
You could just do the filter in the LINQ statement:
var allDeskTopFiles = Directory
.GetFiles(filepath, "*.txt*")
.Where(f => !f.EndsWith("test.txt", StringComparison.InvariantCultureIgnoreCase);
foreach (string file in allDeskTopFiles)
{
// Move all files now
Directory.GetFiles returns the names of files (including their paths) in the specified directory.
So you need to apply a method to extract only the filename
foreach (string file in AllDeskTopFiles)
{
if (Path.GetFileName(file).ToLower() != "test.txt")
{
FileInfo mFile = new FileInfo(file);
if (new FileInfo(d + "\\FileHolder\\" + mFile.Name).Exists == false)
mFile.MoveTo(d + "\\FileHolder\\" + mFile.Name);
}
}
Also creating a FileInfo for every loop just to test the existence or not of the file seems a bit expensive
string destPath = Path.Combine(filepath, "FileHolder");
foreach (string file in AllDeskTopFiles)
{
string fileToMove = Path.GetFileName(file).ToLower();
if (fileToMove != "test.txt")
{
string destFile = Path.Combine(destPath, fileToMove);
if (!File.Exists(destFile))
File.Move(file, destFile);
}
}
You can either check the file name, like this:
DirectoryInfo dirInfo = new DirectoryInfo("old");
foreach (FileInfo fi in dirInfo.GetFiles("*.txt"))
{
if (fi.Name != "test.txt")
File.Copy(fi.FullName, "new/" + fi.Name);
}
Or change your code to check if !file.Contains("text.txt") instead of if file != "test.txt
Following should fix it, A cleaner way now:
private void testmodule()
{
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);
List<String> AllDeskTopFiles = Directory.GetFiles(filepath, "*.txt*").ToList();
foreach (string file in AllDeskTopFiles)
{
//if (file.ToLower().EndsWith("test.txt"))
//{
// FileInfo mFile = new FileInfo(file);
// if (new FileInfo(d + "\\FileHolder\\" + mFile.Name).Exists == false)
// mFile.MoveTo(d + "\\FileHolder\\" + mFile.Name);
//}
FileInfo mFile = new FileInfo(file);
if(mFile.Name.ToLower() != "test.txt")
{
if (new FileInfo(d + "\\FileHolder\\" + mFile.Name).Exists == false)
mFile.MoveTo(d + "\\FileHolder\\" + mFile.Name);
}
}
}

how to sort file in alphanumeric in Fileinfo[] obtained via directory.getfiles and store them in same fileinfo[] array using C#

I need to take all file in particular directory and store them in fileinfo array and sort them alphanumerically.
code snippet
string dir = #"C:\tem";
DirectoryInfo directory = new DirectoryInfo(dir);
if (directory != null)
{
FileInfo[] files = directory.GetFiles("*.bmp");
if (files.Length > 0)
{
Console.WriteLine("Files:");
foreach (FileInfo subFile in files)
{
Console.WriteLine(" " + subFile.Name + " (" + subFile.Length + " bytes)");
}
}
}`
currently i am getting output
test_1.bmp test_11.bmp test_2.bmp
but i want the output like
test_1.bmp,test_2.bmp,test_11.bmp
Thanks
You can use LINQ for that:
if (directory != null)
{
FileInfo[] files = directory.GetFiles("*.bmp");
files.Select(f => f.Name).ToList().
OrderBy(x=> Int32.Parse(x.Substring(x.IndexOf('_') + 1, x.IndexOf('.') - x.IndexOf('_') - 1))).
ToList().ForEach(s => Console.WriteLine(s));
}
The output is:
test_1.bmp
test_2.bmp
test_11.bmp
UPDATE:
// Store as FileInfo array
FileInfo[] sortedFiles = files.OrderBy(x => Int32.Parse(x.Name.Substring(x.Name.IndexOf('_') + 1, x.Name.IndexOf('.') - x.Name.IndexOf('_') - 1))).
ToArray();
// Do whatever you want
foreach (FileInfo item in sortedFiles)
{
Console.WriteLine(string.Format("FullPath -> {0}", item.FullName));
}
public static void Main()
{
string dir = #"C:\tem";
var directory = new DirectoryInfo(dir);
FileInfo[] files = directory.GetFiles("*.bmp");
var sortedFiles=files.ToDictionary(k=>GetIntValueFromString(k.Name),v=>v).OrderBy(entry=>entry.Key);
foreach (var file in sortedFiles)
{
Console.WriteLine(file.Value.Name);
}
Console.Read();
}
static int GetIntValueFromString(string input)
{
var result = 0;
var intString = Regex.Replace(input, "[^0-9]+", string.Empty);
Int32.TryParse(intString, out result);
return result;
}

convert a FileInfo array into a String array C#

I create a FileInfo array like this
try
{
DirectoryInfo Dir = new DirectoryInfo(DirPath);
FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo FI in FileList)
{
Console.WriteLine(FI.FullName);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
And this array holds all the file names in folder = DirPath
I thought of looping through the FileInfo array and copy it to a String array. Is this ok or is there a much cleaner method ?
Using LINQ:
FileList.Select(f => f.FullName).ToArray();
Alternatively, using Directory you can get filenames directly.
string[] fileList = Directory.GetFiles(DirPath, "*.*",
SearchOption.AllDirectories);
If you want to go the other way (convert string array into FileInfo's) you can use the following:
string[] files;
var fileInfos = files.Select(f => new FileInfo(f));
List<FileInfo> infos = fileInfos.ToList<FileInfo>();
the linq is a great soluction, but for the persons who don't want to use linq, i made this function:
static string BlastWriteFile(FileInfo file)
{
string blasfile = " ";
using (StreamReader sr = file.OpenText())
{
string s = " ";
while ((s = sr.ReadLine()) != null)
{
blasfile = blasfile + s + "\n";
Console.WriteLine();
}
}
return blasfile;
}
Try this one
DirectoryInfo directory = new DirectoryInfo("your path");
List<string> Files = (directory.GetFiles().Where(file => file.LastWriteTime >= date_value)).Select(f => f.Name).ToList();
If you don't want a filter with date, you can simply convert with the below code
List<string> logFiles = directory.GetFiles().Select(f => f.Name).ToList();
If you need the full path of the file, you can use FullName instead of Name.

C# copying multiple files with wildcards and keeping file names

I need to copy multiple files from a directory using a textfile that doesnt contain complete info.
NCR.txt:
Red
target directory has in it:
red1.txt
red3.txt
red44.txt
dest directory needs to have:
red1.txt
red3.txt
red44.txt
My code:
System.IO.Directory.CreateDirectory(#"C:\nPrep\" + textBox1.Text + "\\red");
if (checkBox3.Checked)
{
String[] file_names = File.ReadAllLines(#"C:\NCR.txt");
foreach (string file_name in file_names)
{
string[] files = Directory.GetFiles(textBox2.Text, file_name + "*.txt");
foreach (string file in files)
System.IO.File.Copy(file, #"C:\nPrep\" + textBox1.Text + "\\red\\");
}
}
//FileInfo & DirectoryInfo are in System.IO
//This is something you should be able to tweak to your specific needs.
static void CopyFiles(DirectoryInfo source,
DirectoryInfo destination,
bool overwrite,
string searchPattern)
{
FileInfo[] files = source.GetFiles(searchPattern);
//this section is what's really important for your application.
foreach (FileInfo file in files)
{
file.CopyTo(destination.FullName + "\\" + file.Name, overwrite);
}
}
This version is more copy-paste ready:
static void Main(string[] args)
{
DirectoryInfo src = new DirectoryInfo(#"C:\temp");
DirectoryInfo dst = new DirectoryInfo(#"C:\temp3");
/*
* My example NCR.txt
* *.txt
* a.lbl
*/
CopyFiles(src, dst, true);
}
static void CopyFiles(DirectoryInfo source, DirectoryInfo destination, bool overwrite)
{
List<FileInfo> files = new List<FileInfo>();
string[] fileNames = File.ReadAllLines("C:\\NCR.txt");
foreach (string f in fileNames)
{
files.AddRange(source.GetFiles(f));
}
if (!destination.Exists)
destination.Create();
foreach (FileInfo file in files)
{
file.CopyTo(destination.FullName + #"\" + file.Name, overwrite);
}
}
All suggestions were great and thansk for all the advise but this was perfect:
if (checkBox3.Checked)
{
string[] lines = File.ReadAllLines(#"C:\NCR.txt");
foreach (string line in lines)
{
string[] files = Directory.GetFiles(textBox2.Text, line + "*.txt");
foreach (string file in files)
{
FileInfo file_info = new FileInfo(file);
File.Copy(file, #"C:\InPrep\" + textBox1.Text + "\\text\\" + file_info.Name);
}
}
}
string sourceDir = #"c:\";
string destDir = #"c:\TestDir";
var r = Directory.GetFiles(sourceDir, "red*.txt"); //Replace this part with your read from notepad file
foreach (var s in r)
{
var sourceFile = new FileInfo(s);
sourceFile.CopyTo(destDir + "\\" + s.Replace(sourceDir, string.Empty));
}

Categories