How to rename multiple files after specific character in C#? - c#

I am trying to rename multiple files in C# after specific character.
In my folder I have these files:
Application.xml.4589.done
Compatible.xml.8790.done
I want to rename these files like below:
Application.xml
Compatible.xml
Basically after .xml I am looking to remove everything.
Here is the code I am trying:
public static void Main(string[] args)
{
DirectoryInfo d = new DirectoryInfo(#"C:\Test\");
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
{
var extension = f.FullName.Substring(f.FullName.LastIndexOf('.'), f.FullName.Length - 20);
// Need help here
}
}
Can anybody help me with that?
Thanks

You can Split string by . and Take the first two elements from the split array and Join as a string. You will get the desire file name with an extension.
//I showed you minimal example to solve your problem, update your code accordingly.
var infos = new List<string>(){"Compatible.xml.8790.done", "Compatible.xml.8790.done"};
foreach (var f in infos)
{
var newFileName = string.Join(".", f.Split('.').Take(2));
Console.WriteLine(newFileName);
}
Try Online

Related

Adding File and Directory to Array

I have this method that searches all files and folders in "C:\Sharing".
string[] fileArray = Directory.GetFiles(#"C:\Sharing", "*.*", SearchOption.AllDirectories);
And foreach shows me full path of each file. Great. However, since these are in a directory called "Sharing", I want to check and add files that are like
C:\Sharing\Jerry2022\wedding.jpg (array: 'wedding.jpg', 'Jerry2022')
C:\Sharing\snapshot.jpg (array: 'snapshot.jpg')
C:\Sharing\Newsletter\cover-june.webp (array: 'cover-june.webp', 'Newsletter')
So as you can see, I want to add file and subdirectory name to a string array or List, doesnt matter. Excluding "Sharing".
How can I split the results? I know I can use Substring and LastIndexOf("\") + 1 and separate the ending '' but I'm not sure how to match up the filename with the subdir name too.
Any help is appreciated
You can use DirectoryInfo to get the information you want:
C#:
var directoryInfo = new DirectoryInfo(#"C:\Sharing");
if (directoryInfo.Exists)
{
foreach (var fileInfo in directoryInfo.GetFiles("*.*", SearchOption.AllDirectories))
{
var fileName = fileInfo.Name;
Console.WriteLine(fileName);
var directoryName = fileInfo.DirectoryName;
// you can use split to get the directory name array
Console.WriteLine(directoryName);
}
}
I found an other way, use Uri for this scenario:
C#:
string[] fileArray = Directory.GetFiles(#"C:\Sharing", "*.*", SearchOption.AllDirectories);
foreach (var s in fileArray)
{
var uri = new Uri(s);
var uriSegments = uri.Segments.ToArray();
}
You will see each part of the full path, but you may need to use .Trim('/') for each part. Then you can use string.Equals to get directories which you want.
You could split the results using Split
But of course you can also work with FileInfo instead

Show list from last file to first save

I want to reverse the result displayed in a Combobox.
The last saved file would appear first, currently it is the opposite. it appears with this code:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
foreach (string file in files)
{
comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}
According to my research, the solution would be:
.OrderByDescending(p => p.CreationTime).ToArray();
added somewhere. But I don't know. Every attempt I've made has been unsuccessful.
Currently:
101-00.06.52.TXT
101-00.06.54.TXT
101-00.06.56.TXT
Desired outcome:
101-00.06.56.TXT
101-00.06.54.TXT
101-00.06.52.TXT
Does anyone know?
Instead of static method Directory.GetFiles() method, use GetFiles() method from DirectoryInfo class. Apply OrderByDescending() on it.
Directory.GetFiles():
Returns the names of files that meet specified
criteria
Vs
DirectoryInfo.GetFiles():
Returns a file list from the current directory.
Like,
DirectoryInfo di = new DirectoryInfo(#"C:\Test\"); //Get the Directory information
var allTxtFiles = di.GetFiles("*.txt") //Get all files based on search pattern
.OrderByDescending(p => p.CreationTime) //Sort by CreationTime
.Select(x => x.Name); //Select only name from FileInfo object
foreach (string file in allTxtFiles)
{
comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}
I don't know the reason why you problem. But if you want to receive correct result is simple. First try this:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
comboBox1.ItemsSource = files;
if the result is not correct. Use this:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
files = files.Reverse();
comboBox1.ItemsSource = files;

Move files according to searchPattern

I have excel list with file names that I want to move from one folder to another. And I can not just copy paste the files from one folder to another since there are allot of files that do not match the excel list.
private static void CopyPaste()
{
var pstFileFolder = "C:/Users/chnikos/Desktop/Test/";
//var searchPattern = "HelloWorld.docx"+"Test.docx";
string[] test = { "HelloWorld.docx", "Test.docx" };
var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, test.ToString()))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
}
}
I have tried several things but I still think that with a array it would be the easiest way to do it(correct me if I am wrong).
The issue that I face right now is that it can not find any files (there are files under this name.
You can enumerate the files in the directory by using Directory.EnumerateFiles and use a linq expression to check if the file is contained in you string array.
Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d)));
So your foreach would look like
this
foreach (var file in Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d)))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
Actually no, this will not search the directory for pst files. Either build the path yourself using Path.Combine and then iterate over the string-array, or use your approach. With the code above, you need to update the filter, because it will not find any file when given a string[].ToString (). This should do:
Directory.GetFiles (pstFileFolder, "*.pst")
Alternatively, you can iterate over all files without a filter and compare the filenames to your string-array. For this, a List<string> would be a better way. Just iterate over the files like you're doing and then check if the List contains the file via List.Contains.
foreach (var file in Directory.GetFiles (pstFileFolder))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Here, either iterate over the string array or use a List
if (!nameList.Contains (theFileInfo.Name)) continue;
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
I think you need this
var pstFileFolder = "C:/Users/chnikos/Desktop/Test/";
//var searchPattern = "HelloWorld.docx"+"Test.docx";
string[] test = { "HelloWorld.docx", "Test.docx" };
var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/";
// Searches the directory for *.pst
foreach (var file in test)
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var source = Path.Combine(soruceFolder, theFileInfo.Name);
var destination = Path.Combine(pstFileFolder, file);
if (File.Exists(source))
File.Move(file, destination);
}

Look if file contains a specific string and then read that line

I am using this foreach loop to search for files in a directory and then read them.
foreach (string file in Directory.EnumerateFiles(location, "*.MAI"))
Inside this loop I want to search for the line in the file that contains the word "Sended". Is there a way to look for this word and then read that line?
Try it:
var location = #"<your location>";
foreach (string file in Directory.EnumerateFiles(location, "*.MAI"))
{
var findedLines = File.ReadAllLines(file)
.Where(l => l.Contains("Sended"));
}
If you work with big files, you should use ReadLines method, because when you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array.
Another example from msdn:
var files = from file in Directory.EnumerateFiles(location, "*.MAI")
from line in File.ReadLines(file)
where line.Contains("Sended")
select new
{
File = file,
Line = line
};
Full information, look here: https://msdn.microsoft.com/library/dd383503.aspx
If .MAI files are Textfiles try the following:
foreach (string file in Directory.EnumerateFiles(location, "*.MAI"))
{
foreach (string Line in File.ReadAllLines(file))
{
if (Line.Contains("Sended"))
{
//Do your stuff here
}
}
}

A easier way to add in 50pictures?

So i got this piece of code
namespace kortspel
{
public partial class Form1 : Form
{
ArrayList kortlek = new ArrayList();
Image c1 = new Bitmap("C:/Users/Mert95/Documents/Visual Studio 2012/Projects/kortspel/Spelkort/c1.png");
And i don't want to add in 50pictures with a unique name such as Image c2 = blablabla.
Some people have said i need to create a loop, to add in these 50pictures, so is there a easier way instead of adding in 50 Images in the array?
You can use Directory.GetFiles(string path, string searchPattern) to get an array of all the files in a directory matching a given pattern.
Then, just iterate over the files in a loop like this:
string path = "C:/Users/Mert95/Documents/Visual Studio 2012/Projects/kortspel/Spelkort/";
string[] files = Directory.GetFiles(path, "*.png");
List<Bitmap> images = new List<Bitmap>();
foreach (var file in files)
{
images.Add(new Bitmap(file);
}
Yes, Linq is a good way.
string path = #"C:\Users\Public\Pictures\Sample Pictures";
string[] files = Directory.GetFiles(path, "*.jpg");
var result = from jpeg in files.AsEnumerable()
select Image.FromFile(jpeg);

Categories

Resources