How to move to next file - c#

I've searched high and low for days now to figure away to read a directory then edit a text file based off the file names in the directory with each file name replacing a text on a different line. I have came up with the code below but the problem is it changes the text on all lines to the first file name.
DirectoryInfo dinfo1 = new DirectoryInfo(path);
FileInfo[] Files1 = dinfo1.GetFiles("*.*");
string text = File.ReadAllText("path/text.txt");
foreach (FileInfo file in Files1)
{
text = text.Replace("oldtext1", "path" + file.Name);
text = text.Replace("oldtext2", "path" + file.Name);
text = text.Replace("oldtext3", "path" + file.Name);
}
File.WriteAllText("path/text.txt", text);
Note: I have 100 files in the folder and want to add all 100 files to the text in a first to last order or alphabetical order as new files will be added and I want to keep the order.

If your goal is to replace oldtext1 with the first filename and oldtext2 with the second and so forth, then this should be pretty simple:
for (var i = 0; i < Files1.Length; i++)
{
text = text.Replace("oldtext" + (i+1), "path" + Files1[i].Name);
}
We are using a regular for loop because we want to have an index into the Files1 array. Then we build the string to be replaced by concatenating oldtext with i+1 and we replace it with the current filename in the array.
So first time through the loop, we replace:
oldtext1 => filename1
the second time:
oldtext2 => filename2
and so no:
oldtextn => filenamen
Note: I have 100 files in the folder and want to add all 100 files to the text in a first to last order or alphabetical order as new files will be added and I want to keep the order.
Note that the order of files returned by DirectoryInfo.GetFiles is not guaranteed to be in any particular order. You should use Array.Sort to sort them before you run the above loop.

text.Replace("oldtext1", path + file.Name);
After this action, there will be no oldtext1 can be replaced for the next file name,same to oldtext2 and oldtext3,this is why all lines has been changed to the first file name, I think below code will help you
text += file.FullName+Environment.NewLine;

Related

Create Folders out of PDF-Names, crop the foldername and move them into the folder

I want to create a program that gets all the .pdf-filenames (ex: test.pdf -> test) and creates an folder with that name. Also the foldername should be cropped after the first "-" (ex: A539B2AA3-GG-81234278 -> A539B2AA3).
This is the code I have made yet, but I have no clue how to proceed. I'm still a beginner, trying to learn C#:
string path = #"C:\pdfs\";
string[] filenames;
int lengtharray;
filenames = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly)
.Where(s => (Path.GetExtension(s).ToLower() == ".pdf")).ToArray();
lengtharray = filenames.Length;
If someone can help me, I would be very happy.
Sincerely,
breadhead
You can use this code.
1) Directory.GetFiles has a wildcard support, so you can use *.pdf to search for file.
2) I added some validation in the loop, in case there are PDF file that does not have -.
string path = #"C:\pdfs\";
foreach(var file in Directory.GetFiles(path, "*.pdf", SearchOption.TopDirectoryOnly))
{
var newName = Path.GetFileName(file).Split('-');
if (!newName.Any())
continue;
Directory.CreateDirectory(Path.Combine(path,newName[0]));
}
You can simplify your file query, use filenames = Directory.GetFiles(path, "*.pdf", .... and skip the Where()-part. To loop through your list, you can use a foreach (file in filenames). As mentioned you can get the new filename with file.Split("-")[0] or with a regular expression. Then create a directory with Directory.CreateDirectory and move the file in with System.IO.File.Move("oldfilename", "newfilename");. Now you have all the bricks and you only need to glue them together

Need to remove duplicate text from file names dynamically

Due to a bug in their exporter, a client has a list of files where the file name is being duplicated.
For example:
ThisIs-MyFile-1ThisIs-MyFile-1.jpg
ThisIs-MyFile-2ThisIs-MyFile-2.jpg
While fixing the exporter is obviously the best solution, in the meantime, it would be great to be able to correct the files that they've already exported. I would like to iterate over these files and find the duplicate text in each string and remove it.
How might this be implemented?
Thanks.
Edit:
To be clear, the file names do not share the pattern above in that it isn't just a matter of the number changing. Those are simply placeholders for repeated names.
It could just as easily be:
heyHowAreYou-1heyHowAreYou-1.png
ImOkThanksImOkThanks.pdf
If you know that the filename is always duplicated, you can do something like this:
Grab the filename and the extension of the file you want to "fix"
Remove half of the filename (the duplicated part)
Rename the file using the fixed name
So you should end up with something like this
string originalFile = "ThisIs-MyFile-1ThisIs-MyFile-1.jpg";
string fileName = Path.GetFileNameWithoutExtension(originalFile);
string extension = Path.GetExtension(originalFile);
fileName = fileName.Substring(0, fileName.Length / 2);
File.Move(originalFile, $"{fileName}{extension}");
Of course you should find a way to iterate in a folder instead of manually specify the file names, but that is up to you
Here you go
var dir = new DirectoryInfo(folderpath);
var files = dir.GetFiles();
foreach (FileInfo f in files)
{
var oldname = Path.GetFileNameWithoutExtension(f.Name);
var newname = oldname.Substring(0, oldname.Length / 2);
File.Move(f.FullName, f.FullName.Replace(oldname, newname));
}
As commented take the half of the string.
Try this:
fileName = fileName.Substring(0, fileName.Length / 2);
I assume fileName is the name of the file without file extension
Try:
var file = "ThisIs-MyFile-1ThisIs-MyFile-1.jpg";
// Split to remove file extension.
var splits = file.Split(new[] { '.' });
// Take half the file name.
var fileName = splits[0].Substring(0, splits[0].Length/2);
// Add the extension back.
var newFile = $"{fileName}.{splits[1]}";
You could use the FileInfo.Extension property to remove the extension, then substring half the string and concatenate with the extension:
var fileInfo = new FileInfo(filePath);
var nameWithoutExtension = fileInfo.Name.Replace(fileInfo.Extension, string.Empty);
var newName = $"{nameWithoutExtension.Substring(0, nameWithoutExtension.Length / 2)}{fileInfo.Extension}";

Trying to search for specific value within text file

I'm trying to search for a specific value within an array of files. I'm not sure what I'm missing here, but some insight would be great.
I've tried containing all lines from each file into an array that can be read from within an if statement.
void getAssetTag()
{
string path = #"\\SERVER\SHARE\FOLDER";
DirectoryInfo d = new DirectoryInfo(path);//Grabbing Directory
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
foreach (FileInfo file in Files)
{
string[] asset = File.ReadAllLines(file.FullName);
if (asset.Contains(AssetT.Text) == true) {
string allinfo = File.ReadAllText(file.FullName);
Results.Text = allinfo;
}
}
}
The results should output the entire data from the text file contained within AssetT.Textinto Results.Text.
asset is a string[], where each string is a line of text. When you do if (asset.Contains(AssetT.Text)), you're comparing an entire line to AssetT.Text.
If you want to find out if any single line contains AssetT.Text, then we need to call Contains on the line, not the array:
if (asset.Any(line => line.Contains(AssetT.Text))
Also, you're ending up reading the file twice here, once when you do ReadAllLines, and again when you do ReadAllText. Since it seems you will always read the whole file (either to determine that the file doesn't contain the text, or to get all the contents because it does contain the text), you should just do it once.
If you use File.ReadAllText in the beginning, now we have a string representation of the entire file which we can call .Contains on:
foreach (FileInfo file in new DirectoryInfo(path).GetFiles("*.txt"))
{
string asset = File.ReadAllText(file.FullName);
if (asset.Contains(AssetT.Text))
{
Results.Text = asset;
// No use reading more files unless we're going
// to save the contents to another variable
break;
}
}
Note that we break out of the loop since it appears you're setting the contents of the file to a single field of some class, so searching for more files will just overwrite any previous results found.
This can be simplified further using System.Linq extension methods and method chaining. We can also use Directory.GetFiles (which returns a list of file paths) instead, since we don't need a full-blown FileInfo object:
Results.Text = Directory
.GetFiles(path, "*.txt")
.Select(File.ReadAllText)
.FirstOrDefault(fileText => fileText.Contains(AssetT.Text)) ?? Results.Text;

how to seprate an array to 4 segment and print it by 4 thread

I have an array that is some text files path. I want to copy those paths to another folder. by one thread for example execute in 6 seconds. Do you think that if I use for example 4 threads it can be optimized or not ?
and also how I can do that ?
I want to seperate that array to 4 segments and every thread copy its segment path. It's my code that first search *.txt files in special directory and then copy all of them to another folder.
string format = "*.txt";
string directory = lblDirectory.Text;
// it's path of first folder that i search text file in it
DirectoryInfo info = new DirectoryInfo(directory);
if ((info.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
{
Thread t;
string[] files = Directory.GetFiles(directory, format,
SearchOption.AllDirectories);
foreach (var item in files)
{
streamWriter.Write(Path.GetFullPath(item) + "\r\n");
File.Copy(Path.GetFullPath(item), Path.Combine(index,
Path.GetFileName(item)), true);
}
}
I suggest using Parallel Linq (PLinq) and let .Net split the work for you, something like this:
Directory
.EnumerateFiles(directory, format, SearchOption.AllDirectories)
.AsParallel()
.WithDegreeOfParallelism(4)
.ForAll(item => {
//TODO: be sure that streamWriter.Write is thread safe!
streamWriter.Write(Path.GetFullPath(item) + "\r\n");
File.Copy(Path.GetFullPath(item),
Path.Combine(index, Path.GetFileName(item)),
true);
});

How can I replace my txt file with an array?

I made a array out of a txt file and now i want to replace the array in this txt file (replace like in update).
becouse i edited the array, and now i want to replace the txt file again , i hope its possible and i hope its possible with breaklines.
string[] linesa = File.ReadLines("file1.txt").ToArray();
this is the line where i make a array of my txt.
number = Array.IndexOf(linesa, commonElement);
number = number + 1;
email = linesa[number];
linesa[number] = "";
number = number - 1;
linesa[number] = "";
this is the edit i made and now i want to put it back in the txt file this is where i have alot of problems with.
Just use WriteAllLines method. It will replace the contents of the file if the file exists.
File.WriteAllLines("file1.txt", linesa);

Categories

Resources