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);
}
}
}
Related
i need to find and delete all lines wich contain the word "recto",
i did search in stackoverflow forum, but all what i found is do that (delete the line) using path (Directory & FileName).
in my case i want to delete the line contain "recto" in all fils with specific extention (*.txt) in the directory.
thanks for help
here is my code so far
string sourceDir = #"C:\SRCE\";
string destinDir = #"C:\DIST\";
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
using (StreamReader sr_ = new StreamReader
(sourceDir + Path.GetFileName(file)))
{
string line = sr_.ReadLine();
if (line.Contains("recto"))
{
File.Copy(file, destinDir + Path.GetFileName(file));
string holdName = sourceDir + Path.GetFileName(file);
}
sr_.DiscardBufferedData();
sr_.Close();
}
}
}
You can try something like this. You were only identifying the files with the word but not making any try to remove it. At the end, you were copying the files that included the word "recto"
string sourceDir = #"C:\SRCE\";
string destinDir = #"C:\DIST\";
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
using (StreamReader sr_ = new StreamReader
(sourceDir + Path.GetFileName(file)))
{
string res = string.Empty;
while(!sr_.EndOfStream)
{
var l = sr_.ReadLine();
if (l.Contains("recto"))
{
continue;
}
res += l + Environment.NewLine;
}
var streamWriter = File.CreateText(destinDir + Path.GetFileName(file));
streamWriter.Write(res);
streamWriter.Flush();
streamWriter.Close();
}
}
If the files are not really big you can simplify a lot your code reading all lines in memory, processing the lines with Linq and then rewriting the files
string sourceDir = #"C:\SRCE\";
string destinDir = #"C:\DIST\";
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
var lines = File.ReadLines(file);
var result = lines.Where(x => x != "recto").ToArray();
File.WriteAllLines(Path.Combine(destinDir, Path.GetFileName(file)), result);
}
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();
}
}
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;
}
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);
}
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));
}