so i have a listview that displays the filename of the text file thats fine
the problem is foreach textfile i have so say a file is called 8133.txt it has a image file to so 8133.jpg
i want that to match in my listview to the correct textfile
DirectoryInfo di = new DirectoryInfo("C:\\OmGRhys Student System Files - 2019\\");
FileInfo[] files = di.GetFiles("*.txt");
foreach (FileInfo f in files)
{
foreach (string imageFileName in Directory.GetFiles(path, "*.jpg"))
{
listView1.Items.Add(new ListViewItem(new string[] { f.Name, imageFileName }));
}
}
so..
and to keep that pattern for everyfile in the directorys
all textfiles and image files are in the same directory
Try this:
DirectoryInfo di = new DirectoryInfo("C:\\OmGRhys Student System Files - 2019\\");
FileInfo[] files = di.GetFiles("*.txt");
foreach (FileInfo f in files)
{
string imgName = Path.GetFileNameWithoutExtension(f.FullName) + ".jpg";
string imgFile = Path.Combine(di.FullName, imgName);
if (File.Exists(imgFile))
listView1.Items.Add(new ListViewItem(new string[] { f.Name, imgFile }));
}
Related
I have code that steps through a main directory and all the sub directories. The images in each sub directories needs to be renamed as per the folder it is ins name.
C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\\Batch002-190227010418829\PPA14431564096\File1.png
should rename to
C:\Users\alle\Desktop\BillingCopy\uploaded 27-02\Batch002-190227010418829\PPA14431564096\PPA14431564096.png
I can see the code is stepping through every thing but the image isn't beeing renamed and I can't see where I went wrong
while(isTrue)
{
try
{
//write your code here
string filename1 = "1.tif";
string newFileName = "allen.tif";
string[] rootFolder = Directory.GetDirectories(#"C:\Users\alle\Desktop\BillingCopy");
foreach(string dir in rootFolder)
{
string[] subDir1 = Directory.GetDirectories(dir);
foreach(string subDir in subDir1)
{
string[] batchDirList = Directory.GetDirectories(subDir);
foreach(string batchDir in batchDirList)
{
string[] waybillNumberDir = Directory.GetDirectories(batchDir);
foreach(string hawbDir in waybillNumberDir)
{
string waybillNumber = Path.GetDirectoryName(hawbDir);
string[] getFileimages = Directory.GetFiles(hawbDir);
foreach(string imgInDir in getFileimages)
{
File.Copy(imgInDir, Path.Combine(#"C:\Users\alle\Desktop\Copy", string.Format("{0}.{1}", waybillNumber, Path.GetExtension(imgInDir))));
}
}
}
}
}
File.Copy(Path.Combine("source file", filename1), Path.Combine("dest path",
string.Format("{0}{1}", Path.GetFileNameWithoutExtension(newFileName), Path.GetExtension(newFileName))), true);
}
catch { }
}
When querying you can try using Linq to obtain the required data:
// All *.png files in all subdirectories
string rootDir = #"C:\Users\alle\Desktop\BillingCopy";
var agenda = Directory
.EnumerateFiles(rootDir, "*.png", SearchOption.AllDirectories)
.Select(file => new {
oldName = file,
newName = Path.Combine(
Path.GetDirectoryName(file),
new DirectoryInfo(Path.GetDirectoryName(file)).Name + Path.GetExtension(file))
})
.ToArray();
Then we can move (not copy) the files:
foreach (var item in agenda)
File.Move(item.oldName, item.newName);
One Question about coding (Visual Studio C# WindowsformApplication) There have Two folder: (Source and Target) and I build 1 button "Copy".
In "Source" folder have random folders such as "20190401", "20190402", "20190403", "20180401", "20170401" and "20160401". Every these folders have [10] .txt files. What is the coding if I only want to copy all "201904**" folders with [3] .txt files inside it to "Target" folder? Here is my code for now.
Code
** private void button1_Click
{
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/Desktop/Target/";
DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
string directname = "201904";
string filename = ".txt";
foreach (DirectoryInfo newfile in fiDiskfiles)
{
try
{
if (newfile.Name == "2019")
{
foreach (DirectoryInfo direc in newfile.GetDirectories())
if (direc.Name.StartsWith(directname))
{
int count = 0;
foreach (FileInfo file in direc.GetFiles())
{
if (file.Name.EndsWith(filename))
{
count++;
}
}
if (count == 3)
{
DirectoryCopy(direc.FullName,Path.Combine(TO_DIR,direc.Name), true);
count = 0;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("success");
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}**
I expect after I click a button,
output is automatically copy all folders Name Start With "201904**" with [3] text files inside from "Source" folder to "target" folder.
I reckon you can search the directory with names directly using linq and can copy the sub folders/files inside it like below. It will give you the flexibility of filtering folders/files/skipping/taking n folders/files
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/Desktop/Target/";
string searchText = "201904";
string extension = "txt";
IEnumerable<string> dirs = Directory.EnumerateDirectories(FROM_DIR, "*", SearchOption.AllDirectories)
.Where(dirPath=>Path.GetFileName(dirPath.TrimEnd(Path.DirectorySeparatorChar)).StartsWith(searchText));
foreach (string dir in dirs)
{
string destDirPath = dir.Replace(FROM_DIR, TO_DIR);
if (!Directory.Exists(destDirPath))
Directory.CreateDirectory(destDirPath);
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.EnumerateFiles(dir, string.format("*.{0}",extension),
SearchOption.AllDirectories))// Here you can skip/take n files if u need
File.Copy(newPath, newPath.Replace(FROM_DIR, TO_DIR), true);
}
Have tested with sub folders and files inside source folder as well. Hope it helps.
So I want to log what happens when I backup files but I'm not sure how to make it work for files in subdirectories aswell.
Right now I have this code that works for all files in the selected directory but doesn't work for subdirectory files
private void LogBackup(string sourceDirName, string destDirName)
{
List<string> lines = new List<string>();
string logDestination = this.tbox_LogFiles.Text;
string dateString = DateTime.Now.ToString("MM-dd-yyyy_H.mm.ss");
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
lines.Add("FILES TO COPY:");
lines.Add("--------------");
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files
.Where(f => !extensionsToSkip.Contains(f.Extension) && !filesToSkip.Contains(f.FullName)).ToList())
{
string desttemppath = Path.Combine(destDirName, file.Name);
string sourcetemppath = Path.Combine(sourceDirName, file.Name);
lines.Add("SOURCE FILE:");
lines.Add(sourcetemppath);
lines.Add("DESTINATION FILE:");
lines.Add(desttemppath);
lines.Add("");
}
foreach (DirectoryInfo subdir in dirs
.Where(f => !foldersToSkip.Contains(f.FullName)))
{
//NOT SURE WHAT TO WRITE HERE
}
using (StreamWriter writer = new StreamWriter(logDestination + #"\LOG " + dateString + ".txt"))
{
foreach (string line in lines)
{
writer.WriteLine(line);
}
}
}
Any ideas please?
Include the SearchOption.AllDirectories and you will get all sub directories:
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories("*", SearchOption.AllDirectories);
when you now loop through the directories, you will have also the first level of subdirectories and for each directory just get the files that it contains
foreach (DirectoryInfo subdir in dirs)
{
FileInfo[] files = subdir.GetFiles();
......
I am new to C# programming.Please suggest me how to retrieve the fullpath but using only file.Name in my code as I only want to enter file name in my listBox not full path
My code is:
listBox1.DataSource = GetFolder("..\\video\\");
private static List<string> GetFolder(string folder)
{
List<string> FileList = new List<string>();
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
foreach (FileInfo file in allFiles)
{
FileList.Add(file.FullName);
}
return FileList;
}
FileInfo(path).Directory.FullPath
Your actual problem of your code is missing semi-colon for this line
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
It should be
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories);
If I get you right, you want the FullPath as value but only the FileName displayed. To achieve this, you could use a List of FileInfos containing both of these values and tell the ListBox, which member is the value and which one should be displayed:
this.listBox1.DisplayMember = "Name";
this.listBox1.ValueMember = "FullName";
listBox1.DataSource = GetFolder("..\\video\\");
Player.URL = Convert.ToString(listBox1.SelectedValue); // Instead of SelectedItem
private static List<FileInfo> GetFolder(string folder)
{
List<FileInfo> fileList = new List<FileInfo>();
foreach (FileInfo file in new DirectoryInfo(folder).GetFiles("*.mpg", SearchOption.AllDirectories))
{
fileList.Add(file);
}
return fileList;
}
FileList.Add(file.FullName);
Please Change this line like below
FileList.Add(file.Name );
listBox1.DataSource = GetFolder("..\\video\\");
private static List<string> GetFolder(string folder)
{
List<string> FileList = new List<string>();
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
foreach (FileInfo file in allFiles)
{
FileList.Add(file.Name);
}
return FileList;
}
I need to move all files from source folder to destination folder. How can I easily extract file name from file path name?
string newPath = "C:\\NewPath";
string[] filePaths = Directory.GetFiles(_configSection.ImportFilePath);
foreach (string filePath in filePaths)
{
// extract file name and add new path
File.Delete(filePath);
}
Try the following:
string newPathForFile = Path.Combine(newPath, Path.GetFileName(filePath));
Path.GetFileName(filePath)
use DirectoryInfo and Fileinfo instead of File and Directory, they present more advanced features.
DirectoryInfo di =
new DirectoryInfo("Path");
FileInfo[] files =
di.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo f in files)
f.MoveTo("newPath");
You may want to try the FileInfo.MoveTo method (code example at the following link):
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.moveto.aspx
You can do it like this:
string newPath = "C:\\NewPath";
string[] filePaths = Directory.GetFiles(_configSection.ImportFilePath);
foreach (string filePath in filePaths)
{
string newFilePath = Path.Combine(newPath, Path.GetFileName(filePath);
File.Move(filePath, newFilePath);
}