This question already has answers here:
Getting the folder name from a full filename path
(12 answers)
Closed 5 months ago.
I have code which looks for .ini files in all folders in root directory. I want to show only folder those .ini files are in, that is only info relevant to me, because it shows different project names. But as far I can figure it out I can only show full path to file or only file itself in listbox. Any help?
My code:
private void Form1_Load(object sender, EventArgs e)
{
string rootdir = #"C:\Users\isaced1\Desktop\test"; //root directory of all projects
string[] files = Directory.GetFiles(rootdir, "Project_config.ini", SearchOption.AllDirectories); //searches for specific .ini files in all directories whithin rood directory
//cycles through all .ini files and adds it to lsitbox1 or listbox2
foreach (string item in files)
{
string fileContents = File.ReadAllText(item); //reads all .ini files
const string PATTERN = #"OTPM = true"; //search pattern in .ini files
Match match = Regex.Match(fileContents, PATTERN, RegexOptions.IgnoreCase); //matches pattern with content in .ini file
if (match.Success)
{
listBox1.Items.Add(Path.GetDirectoryName(item)); //if match is successfull places file in lisbox1
listBox1.ForeColor = Color.Green;
}
else
{
listBox2.Items.Add(Path.GetDirectoryName(item)); //if match is unsuccessfull places file in lisbox2
listBox2.ForeColor = Color.Red;
}
}
}
listBox1.Items.Add(new Uri(Path.GetDirectoryName(item)).Segments.Last())
This one worked perfectly!
Related
I'm working with C# in ASP.net framework. I need to make a copy of files and save them.
File.Copy("fileFirst.txt", "fileSecond.txt"); seems to work for that.
However I have multiple files and I need to do this for every single file. Instead of having to type the names for every single file how can I simply have a copy of the file such that it has the original filename with a -new appended on it's back.
Original file: fileFirst.txt
Copy of the file: fileFirst-new.txt
NOTE: It has to to do this for as many files as I have and not just one.
This code lists all the files in a directory and copies them to the same folder but with a different name.
private static void RenameDirectoryFiles()
{
string pathfile = #"M:\_downloads\";
string[] filePaths = Directory.GetFiles(pathfile);
foreach (string filePath in filePaths)
{
try
{
string dire = Path.GetDirectoryName(filePath);
string name = Path.GetFileNameWithoutExtension(filePath);
string exte = Path.GetExtension(filePath);
File.Copy($"{filePath}", $"{pathfile}\\{name}-New{exte}");
}
catch (Exception e)
{
Console.WriteLine("Error File Copy");
}
}
}
The product I'm using is a Beijer HMI, currently i can generate a report and save it to a known location (my desktop - C:\Users\mrdav\Desktop).
I need to be able to search on my desktop for a file extension .xls and change its name.
When the report is generated by the HMI, it uses the date and time which means when the file is generated the name will be different every time.
On the press of a button i need to search my desktop for the .xls file and change its name to a variable.
// This is my variable with my program
string NewName = Globals.Tags.Tag1.Value;
The code that is generated needs to sit within the below example.
public partial class Screen1
{
void Button1_Click(System.Object sender, System.EventArgs e)
{
// Code to be added here...
}
}
Hopefully someone can help, I’m using windows compact framework so limited on functionality.
Any questions please let me know.
Thanks in advance,
Dave
Here is an example how you can do that:
DirectoryInfo dir = new DirectoryInfo(sExportPath);
FileInfo[] Files = dir.GetFiles("*.csv");
foreach(FileInfo file in Files )
{
// rename file
System.IO.File.Move(file.FullName, GenerateNewFileName());
}
//elsewhere in the class
private string GenerateNewFileName()
{
//here is where you implement creating or getting the filename that you want your file to be renamed to. An example might look like the below
string serialNumber = GetSerialNumber(); //Get the serial number that you talked about in the question. I've made it a string, but it could be an int (it should be a string)
return Path.ChangeExtension(serialNumber,".xls"); //to use path you will need a using statement at the top of your class file 'using System.IO'
}
This seems to work...but i know its not as tidy as it could be.
Any suggestions?
Thanks to all that helped, got there in the end!
void Button_Click(System.Object sender, System.EventArgs e)
{
try
{
// Location for new file
string NewFileName = #"c:\users\mrdav\desktop\testfolder\";
// Add varibale name to new file
NewFileName += Globals.Tags.Tag1.Value;
// add .xls extention to new file
NewFileName += ".xls";
//show new file name to check all ok
MessageBox.Show (NewFileName);
//search for .xls in known directory
DirectoryInfo di = new DirectoryInfo(#"c:\users\mrdav\desktop");
FileInfo[] Files = di.GetFiles("*.xls");
// if files exist with .xls extention
foreach(FileInfo file in Files )
{
// show full file name
MessageBox.Show (file.FullName);
//rename old file to new file name and move to new folder
File.Move(file.FullName, NewFileName);
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
Trying to copy all files/directories inside a directory to a new location that I create.
Users select the 'backup drive' to work with to in a combobox, then when they click the backup desktop button it simply creates a backup directory on that drive and copies all the files into that directory.
The backup directory gets created on the drive appropriately - but the first file it hits it kicks off an error.
private void backupDesktopButton_Click(object sender, EventArgs e)
{
//set the destionationLocation to the selectedDrive
string selectedDrive = backupDriveCombo.SelectedItem.ToString();
string destinationLocation = selectedDrive+"Backups-" + DateTime.Now.Month.ToString()+"-"+DateTime.Now.Year.ToString()+"\\Desktop\\";
if (!Directory.Exists(destinationLocation))
{
Directory.CreateDirectory(destinationLocation);
}
string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string[] fileList = Directory.GetFiles(desktopFolder);
foreach (string file in fileList)
{
//move the file
File.Copy(file, destinationLocation);
}
}
I get the error:
IOException was unhandled.
The filename, directory name, or volume label syntax is incorrect.
In the 'Autos' window (VS2010) I see the locations are set correctly:
destinationLocation = the appropriate directory (C:\Backups-8-2016\Desktop\)
file = the appropriate first file (C:\Users\myusername\Desktop\myshortcut.url)
What am I missing? I have all rights to be able to copy/paste/create things and the directory to store it gets created - just a problem moving the file.
From the documentation https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
the second parameter:
The name of the destination file. This cannot be a directory or an existing file.
you need to concat the filename to the folder.
Try something like this
string[] fileList = Directory.GetFiles(desktopFolder);
foreach (string file in fileList)
{
string targetFile = Path.Combine(destinationLocation, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Copy(file, targetFile);
}
This question already has answers here:
Find a file with a certain extension in folder
(6 answers)
Closed 7 years ago.
How to check if any .txt file exists in a folder?
If the folder still have .txt file output a error messagebox.
Thx all! Actually i want to make a function can check any .txt file exists in a folder. If yes write a error message to eventLog.
Final My code:
System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
DirectoryInfo di = new DirectoryInfo(#"c:/Users/Public/Definitions");
FileInfo[] TXTFiles = di.GetFiles("*.txt");
foreach (var fi in TXTFiles)
{
if (fi.Exists)
{
appLog.Source = "Definitions Folder still have text files";
appLog.WriteEntry("Still have txt files.");
}
}
You can check like below :
DirectoryInfo dir = new DirectoryInfo(#"c:\Directory");
FileInfo[] TXTFiles = dir.GetFiles("*.txt");
if (TXTFiles.Length == 0)
{
//No files present
}
foreach (var file in TXTFiles)
{
if(file.Exists)
{
//.txt File exists
}
}
You can use the Directory.EnumerateFiles like this:
if(Directory.EnumerateFiles(folder, "*.txt",SearchOption.TopDirectoryOnly).Any())
Foo();
See more here Directory.EnumerateFiles Method
You can do it like this
string[] files = System.IO.Directory.GetFiles(path, "*.txt");
if(files.Length >= 1)
{
MessageBox.Show("Error Message ... Your folder still have some Txt files left");
// or
Console.WriteLine("Error Message ... Your folder still have some Txt files left");
}
I have some files (.txt, word, excel files) in "C:\ABC\Temp" and I want to move all the .txt files into "C:\ABC\Text", but I'm getting a FileNotFoundException.
Please find attached code.
static void Main()
{
string sp = #"C:/ABC/Temp";
string dp = #"C:/ABC/TextFiles";
string[] fileList=Directory.GetFiles(sp);
foreach(string file in fileList)
{
if (file.EndsWith(".txt"))
{
File.Move(sp,dp);
}
}
}
}
}
You're trying to move the entire directories with File.Move.
You have to specify the file name as well:
File.Move(file, Path.Combine(dp, Path.GetFileName(file)));