Cannot show the content properly in looping - c#

I have write a c# code to retrieve all the file names follow by printing one of the information inside. Example File contains (file1.mht, file2.mht, file3.mht). Maybe the contain inside is (aaaaaa, bbbbbb, cccccc) follow the sequence of the file.
Example out output:
file1.mht aaaaaa
file2.mht bbbbbb
file3.mht cccccc
But I encounter the problem it cannot loop the file name follow by showing the content inside. Anyone can helps? Current result is it show all the directory first and only done the work for the first one in directory.
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Specialized;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
string str = "";
string mht_text = "";
string directory = "";
string listInfo = "";
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}
foreach (char filePath in directory)
{
//Here is my work to retrieve the data in the file
Console.WriteLine("Names:" + str + " " + "Component:" + component);
Console.ReadKey();
}
}
}
}

From your question I understand that you want to print the file name followed by the content of the same, if so you can try:
DirectoryInfo mht_file = new DirectoryInfo(#"C:\Users\liewm\Desktop\SampleTest\");
FileInfo[] Files = mht_file.GetFiles("*.mht");
foreach (FileInfo file in Files)
{
// read the content of the file
var content = File.ReadAllText(file.FullName);
// from your question "Example out output: file1.mht aaaaaa"
Console.WriteLine($"{file.Name} {content}");
}

only done the work for the last one in directory.
Yes, that's cause your directory variable is a string string directory = "" which will get overridden by the last value of loop iteration. You rather want to store in a string[] rather if you want to process all of them.
foreach (FileInfo file in Files)
{
str = file.Name;
directory = mht_file + str;
Console.WriteLine(directory);
}

Please try this.
foreach (FileInfo file in Files)
{
str = file.Name;
directory += mht_file + str;
Console.WriteLine(directory);
}

Related

How can I compare variables and set a variable to new text found in one of the variables in c#

I need to compare files found in a directory with another directory and print the files new files found in a directory into the console. I have it setup so it takes the files and assigns it to a variable. The other directory is assigned to another variable. How can I print the new data in one of the variables to command prompt?
The language I am using is c#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Write the path of the old file folder: ");
string path = Console.ReadLine();
listFilesFromDirectory(path);
Console.Write("Write the path of the new file folder: ");
string pathTwo = Console.ReadLine();
listFilesFromDirectoryMore(pathTwo);
Console.WriteLine("Press Enter to continue:");
Console.Read();
}
static void listFilesFromDirectory(string workingDirectory)
{
// get a list of files in a directory,
// based upon a path that is passed into the function
string[] filePaths = Directory.GetFiles(workingDirectory);
foreach (string filePath in filePaths)
{
// use the foreach loop to go through the entire
// array one element at a time write out
// the full path and file name of each of the
// elements in the array
Console.WriteLine(filePath);
string oldfile = (filePath);
}
}
static void listFilesFromDirectoryMore(string workingDirectoryTwo)
{
// get a list of files in a directory,
// based upon a path that is passed into the function
string[] filePathsTwo = Directory.GetFiles(workingDirectoryTwo);
foreach (string filePathTwo in filePathsTwo)
{
// use the foreach loop to go through the entire
// array one element at a time write out
// the full path and file name of each of the
// elements in the array
Console.WriteLine(filePathTwo);
string newfile = (filePathTwo);
}
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Write the path of the old file folder: ");
string pathA = Console.ReadLine();
Console.Write("Write the path of the new file folder: ");
string pathB = Console.ReadLine();
Console.WriteLine("Press Enter to continue:");
List<string> folderA = new List<string>();
foreach (string filePath in Directory.GetFiles(pathA))
{
folderA.Add(Path.GetFileName(filePath));
}
List<string> folderB = new List<string>();
foreach (string filePath in Directory.GetFiles(pathB))
{
folderB.Add(Path.GetFileName(filePath));
}
Console.Write("New files in folder" + pathA + " : ");
Print(folderA, folderB);
Console.WriteLine("------------------------------------");
Console.Write("New files in folder" + pathB + " : ");
Print(folderB, folderA);
Console.Read();
}
static void Print(List<string> lstA, List<string> lstB)
{
foreach (string fileName in lstA)
{
if (!lstB.Contains(fileName))
{
Console.Out.WriteLine(fileName);
}
}
}
}
}

How to change Unix Line feed to Windows Line Feed with C#

I'm trying to write a unix2dos program to alter the line feeds of text files.
The problem is instead of altering the contents of a text file, the file name was appended instead.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace unix2dos
{
class Program
{
static void Main(string[] args)
{
string[] filePaths = Directory.GetFiles(#"c:\textfiles\", "*.txt");
foreach (string file in filePaths)
{
string[] lines = File.ReadAllLines(file);
foreach (string line in lines)
{
string replace = line.Replace("\n", "\r\n");
File.WriteAllText(file, replace);
}
}
}
}
}
Because you are writing the string and overwriting it.
Try this:
string[] filePaths = Directory.GetFiles(#"c:\textfiles\", "*.txt");
foreach (string file in filePaths)
{
string[] lines = File.ReadAllLines(file);
List<string> list_of_string = new List<string>();
foreach (string line in lines)
{
list_of_string.Add( line.Replace("\n", "\r\n"));
}
File.WriteAllLines(file, list_of_string);
}

how to get files in sub folders

I'm creating C# console app to clean up my download folder in windows
my app work fine for video file and move and and delete it from download folder. but how can I make get get the file in subfolder and add it to my files array?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace CleanDownloadFolder
{
class Program
{
static void Main(string[] args)
{
string sourcePath = #"C:\Users\___\Downloads";
string targetPath = #"C:\Users\__\Videos";
CopyDirectory(sourcePath, targetPath);
}
private static void CopyDirectory(string sourcePath, string targetPath)
{
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
string fileName = null;
string destFile = null;
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
if (Path.GetExtension(fileName) == ".avi")
{
System.IO.File.Copy(s, destFile, true);
System.IO.File.Delete(s);
}
}
}
}
}
}
Directory.GetFiles has an overload that could be used to get the list of files in subdirectories
string[] files = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories);
The remainder of your code should work as is, however, if your are interested only in the AVI files then you could put that extension directly in the GetFiles call. In that way you get only AVI files and your code could be simplified removing the if
string[] files = Directory.GetFiles(sourcePath. "*.AVI", SearchOption.AllDirectories);
string fileName = null;
string destFile = null;
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = Path.GetFileName(s);
destFile = Path.Combine(targetPath, fileName);
File.Copy(s, destFile, true);
File.Delete(s);
}
I suggest also to add a using System.IO; at the top of your code file to avoid all of that full namespace typing required without the using

Change extensions of all files in a directory

I don't get an error, but the extension isn't changed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string filename;
string[] filePaths = Directory.GetFiles(#"c:\Users\Desktop\test\");
Console.WriteLine("Directory consists of " + filePaths.Length + " files.");
foreach(string myfile in filePaths)
filename = Path.ChangeExtension(myfile, ".txt");
Console.ReadLine();
}
}
}
Path.ChangeExtension only returns a string with the new extension, it doesn't rename the file itself.
You need to use System.IO.File.Move(oldName, newName) to rename the actual file, something like this:
foreach (string myfile in filePaths)
{
filename = Path.ChangeExtension(myfile, ".txt");
System.IO.File.Move(myfile, filename);
}
Ìf you want to change the extension of a file, call File.Move().
This only changes extension of path and not of file.
Reason: Since ChangeExtension is called of Path.ChangeExtension. For file, use System.IO. File Class and its methods.
The documentation for method ChangeExtension says that:
Changes the extension of a path string.
It doesn't say that it changes extension for a file.
I think this is roughly equivalent (correct) code:
DirectoryInfo di = new DirectoryInfo(#"c:\Users\Desktop\test\");
foreach (FileInfo fi in di.GetFiles())
{
fi.MoveTo(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length - 1) + ".txt"); // "test.bat" 8 - 3 - 1 = 4 "test" + ".txt" = "test.txt"
}
Console.WriteLine("Directory consists of " + di.GetFiles().Length + " files.");
Console.ReadLine();

How to get only filenames within a directory using c#?

When I use the line of code as below , I get an string array containing the entire path of the individual files .
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf");
I would like to know if there is a way to only retrieve the file names in the strings rather than the entire paths.
You can use Path.GetFileName to get the filename from the full path
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
.Select(Path.GetFileName)
.ToArray();
EDIT: the solution above uses LINQ, so it requires .NET 3.5 at least. Here's a solution that works on earlier versions:
private string[] pdfFiles = GetFileNames("C:\\Documents", "*.pdf");
private static string[] GetFileNames(string path, string filter)
{
string[] files = Directory.GetFiles(path, filter);
for(int i = 0; i < files.Length; i++)
files[i] = Path.GetFileName(files[i]);
return files;
}
You can use the method Path.GetFileName(yourFileName); (MSDN) to just get the name of the file.
You could use the DirectoryInfo and FileInfo classes.
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");
//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;
string[] fileEntries = Directory.GetFiles(directoryPath);
foreach (var file_name in fileEntries){
string fileName = file_name.Substring(directoryPath.Length + 1);
Console.WriteLine(fileName);
}
There are so many ways :)
1st Way:
string[] folders = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
string jsonString = JsonConvert.SerializeObject(folders);
2nd Way:
string[] folders = new DirectoryInfo(yourPath).GetDirectories().Select(d => d.Name).ToArray();
3rd Way:
string[] folders =
new DirectoryInfo(yourPath).GetDirectories().Select(delegate(DirectoryInfo di)
{
return di.Name;
}).ToArray();
You can simply use linq
Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));
Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetNameOfFiles
{
public class Program
{
static void Main(string[] args)
{
string[] fileArray = Directory.GetFiles(#"YOUR PATH");
for (int i = 0; i < fileArray.Length; i++)
{
Console.WriteLine(fileArray[i]);
}
Console.ReadLine();
}
}
}

Categories