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();
}
}
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);
}
When user uploads multiple documents I am storing their files in my project like this:
Guid id;
id = Guid.NewGuid();
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(id + item.FileName));
item.SaveAs(filePath);
So files are saved like this in my project:
1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt
bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt
Now when creating zip files I am getting same name of this files when extracting zip files but I don't want guid in my file name after user downloads file.
However I have tried to remove guid from my file name but getting error System.IO.FileNotFoundException.
This is my code:
using (var zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
string[] str1 = str .Split(',');
foreach (var item in str1)
{
string filePath = Server.MapPath("~/Uploads/" + item.Substring(36));//as guid are of 36 digits
zip.AddFile(filePath, "files");
}
zip.Save(memoryStream);//Getting error here
}
ZipFile is throwing an exception because it can't find the file on disk as you have given it a name of a file that does not exist (by doing a .Substring()). To make it work you would have to rename the file using File.Copy with your new file name and then give that same file name to Zip.AddFile().
var orgFileName = "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt";
var newFileName = orgFileName.Substring (36);
File.Copy (orgFileName, newFileName, true);
zip.AddFile (newFileName);
You should use archive and ArchiveEntry. The rough code snipets how to do it (i don't test it):
using(var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) {
{
//using(var zip = new ZipFile()) {
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
//string[] str = str.Split(',');
foreach(var item in str) {
using(var entryStream = archive.CreateEntry("files/" + item.Substring(36)).Open()) {
string filePath = Server.MapPath("~/Uploads/" + item);
var content = File.ReadAllBytes(filePath);
entryStream.Write(content, 0, content.Length);
}
}
}
}
sample for using DotNetZip:
using (ZipFile zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" };
foreach(var item in str) {
string filePath = Server.MapPath("~/Uploads/" + item);
var content = File.ReadAllLines(filePath);
ZipEntry e = zip.AddEntry("files/" + item.Substring(36), content);
}
}
zip.Save(memoryStream);
}
Taking source from #kevin answer i have manage to solve this:
List<string> newfilename1 = new List<string>();
using (var zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
string[] str1 = str .Split(',');
foreach (var item in str1)
{
string filePath = Server.MapPath("~/Uploads/" + item);
string newFileName = Server.MapPath("~/Uploads/" + item.Substring(36));
newfilename1.Add(newFileName);
System.IO.File.Copy(filePath,newFileName);
zip.AddFile(newFileName,"");
}
zip.Save(memoryStream);
foreach (var item in newfilename1)
{
System.IO.File.Delete(item);
}
}
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);
}
}
}
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.
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));
}