Create a text file based on the folder and the file name - c#

I have 10 folders (C:\Import)
Folder1
Folder2
.
.
Folder10
Each folder have some .txt and .html files.
Let me take example of Folder1 having 3 documents
file.txt
file2.html
file3.txt
files in it.
I need script to read the folder and create a txt file in below format.
Folder name 'separator' file name without extension 'separator' filename with extension
So output text file should be :
Folder1:file:file.txt
Folder1:file2:file2.html
Folder1:file3:file3.txt
and Move html, txt files and newly create text file too C:\Output.
This has to be repeated for all the 10 folders and all the corresponding files and created text file should be dropped to same C:\Output
Tried below :
1:
foreach (string file in Directory.GetFiles("C:\\Import\\", "*.html", SearchOption.AllDirectories))
{
string contents = File.ReadAllText(file);
}
2:
public static List<string> AllFilesInFolder(string folder)
{
var result = new List<string>();
foreach (string f in Directory.GetFiles(folder))
{
result.Add(f);
}
foreach (string d in Directory.GetDirectories(folder))
{
result.AddRange(AllFilesInFolder(d));
}
return result;
}

I would suggest you to write PowerShell script. The file manipulation is much easier in powershell, and you can always use .NET libriaries.
Please, take a look at this link, it's Microsoft doc about "Working with Files and Folders" using PowerShell.
But if you don't want to use PowerShell, you can do something like that:
using System;
using System.IO;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("APP START");
string inputDirectory = #"C:\Import\";
string outputDirectory = #"C:\Output\";
FileStream stream = File.Create(outputDirectory + "report.txt");
string [] folders = Directory.GetDirectories(inputDirectory);
foreach(String path in folders)
{
Directory.CreateDirectory(path.Replace(inputDirectory, outputDirectory));
string[] files = Directory.GetFiles(path);
foreach (String file in files)
{
String record = ConvertPathToReportFormat(file);
stream.Write(Encoding.UTF8.GetBytes(record), 0, record.Length);
File.Copy(file, file.Replace(inputDirectory, outputDirectory));
}
}
stream.Close();
Console.WriteLine("DONE");
Console.ReadKey();
}
private static String ConvertPathToReportFormat(string path)
{
string [] splitedPath = path.Split('\\');
string[] splitedName = splitedPath[splitedPath.Length - 1].Split('.');
String folder = splitedPath[splitedPath.Length - 2];
String name = splitedName[0];
String extension = splitedName[1];
return String.Format("{0}:{1}:{2}.{3}\n", folder, name, name, extension);
}
}
}
This little program copy files from one directory to another, and generates report file (report.txt) in following format:
Folder1:File:File.html
Folder1:File:File.txt
Folder1:File2:File2.html
Folder1:File2:File2.txt
Folder1:File3:File3.html
Folder1:File3:File3.txt

Related

Files Copied in the Dropbox folder are treating differently than the original file names

I am using Windows 10 and I have two folders namely Source and Destination. The Destination folder is inside a Dropbox. I have two methods CopySourceFilesToDestination and SynchronizeSourceAndDestination. Fist method copies all folders and files from source to the destination while the second method checks whether the particular filename is present or not in Source folder and if it didn't find the filename in the source it deletes the particular file from the Destination folder. Now I have few files named as below and I don't need to care about the content in the files.
E:\Source\A0000000001\20162356312-Future of Utopia in History. Hayden
White. Historein 7.pdf
E:\Source\T0000000142\20162350775-Étienne Geoffroy Saint-Hilaire,
1772-1844 a visionary naturalist. Hervé Le Guyader.pdf
E:\Source\T0000000403\2016242657-Reveries of the solitary walker;
Botanical writings; and Letter to Franquières. Jean Jacques
Rousseau.pdf
E:\Source\T0000000428\2016243154-Science of Literature- essays on an
incalculable difference.Helmut Müller-Sievers.pdf
When I run my program copies files to the Destination but my SynchronizeSourceAndDestination method deletes all the files expect the first file in the list which doesn't contain any UTF-8 characters.
using System;
using System.IO;
namespace DropboxDemo
{
class Program
{
private static string lookupDirectory = #"E:\Source";
private static string backupDirectory = #"C:\Users\SIMANT\Dropbox \Destination";
static void Main(string[] args)
{
Console.WriteLine("Please wait while copying files.");
CopySourceFilesToDestination(lookupDirectory);
Console.WriteLine("Please wait while synchronizing files.");
SynchronizeSourceAndDestination(backupDirectory);
Console.ReadLine();
}
public static void SynchronizeSourceAndDestination(string dir)
{
foreach (string file in Directory.GetFiles(dir))
{
string destFilePath = file.Replace(backupDirectory, lookupDirectory);
if (!File.Exists(destFilePath))
{
// Delete file from Backup
File.Delete(file);
}
}
foreach (string directory in Directory.GetDirectories(dir))
{
string destinationDirectory = directory.Replace(backupDirectory, lookupDirectory);
if (!Directory.Exists(destinationDirectory))
{
Directory.Delete(directory, true);
continue;
}
SynchronizeSourceAndDestination(directory);
}
}
public static void CopySourceFilesToDestination(string dir)
{
foreach (string file in Directory.GetFiles(dir))
{
string destFilePath = file.Replace(lookupDirectory, backupDirectory);
if (!File.Exists(destFilePath))
{
File.Copy(file, destFilePath);
}
else
{
// Override the existing file
File.Copy(file, destFilePath, true);
}
}
foreach (string directory in Directory.GetDirectories(dir))
{
//Create directory if not present in the destination
string destinationDirectory = directory.Replace(lookupDirectory, backupDirectory);
if (!Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
}
CopySourceFilesToDestination(directory);
}
}
}
}
In the second time, I just copied all files from Destination (which is inside Dropbox) to the Source folder and rerun the program and now it doesn't delete the files. Why am I getting this behaviour? I think when a file is copied to Dropbox, it represents the same file names (what we see from my eyes) in a different way. Could you please help me overcome this issue?
To make my solution workable I changed extended ASCII character by pressing É (Alt + 144), é (Alt + 130). I think it was because the file creator did some copy and paste of the characters directly.

Directory.CreateDirectory() does not create folder within ZipFile

I am trying to zip together all folders and their contents into a zip file. From what I have researched (through StackOverflow and Microsoft), Directory.CreateDirectory(Path) should create the given directory. However, my ZipFile is showing up empty.
For example, I have a folder (C:\Users\smelmo\Desktop\test) with the subfolders (0001, 0002) in it. Within 0001 and 0002 are other documents. I am wanting to zip 0001 and 0002 together within the test folder. This is what I have so far:
// Open the directory of the target folder
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
// Grab each directory within the target folder
foreach (var directoryName in Directory.GetDirectories(strStartPath))
{
// Add each directory to the ZipFile
Directory.CreateDirectory(directoryName);
}
}
This does not produce anything. HOWEVER, I also have code that will grab ALL files within the subfolders and place them in the ZipFile.
// Open the directory of the target folder
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
// Grab each directory within the target folder
foreach (var directoryName in Directory.GetDirectories(strStartPath))
{
//Grab all files in each directory
foreach (var filePath in Directory.GetFiles(directoryName))
{
var fileName = Path.GetFileName(#filePath);
// Place each directory and its repsective files in the zip file
var entry = archive.CreateEntryFromFile(filePath, fileName);
}
}
}
But this does not place subfolders 0001 and 0002 in it, just the CONTENTS of 0001 and 0002. I am wanting 0001 and 0002 and their respective contents.
Edited:
If you are looking for more control, you can just create a function that adds files to a zip archive. You can then use recursion to add any subfolders and files.
First you can define a function that accepts a zip archive to add files to:
public void AddFolderToZip(ZipArchive archive, string rootPath, string path, bool recursive)
{
foreach (var filePath in Directory.GetFiles(path))
{
//Remove root path portion from file path, so entry is relative to root
string entryName = filePath.Replace(rootPath, "");
entryName = entryName.StartsWith("\\") ? entryName.Substring(1) : entryName;
var entry = archive.CreateEntryFromFile(filePath, entryName);
}
if (recursive)
{
foreach (var subPath in Directory.GetDirectories(path))
{
AddFolderToZip(archive, rootPath, subPath, recursive);
}
}
}
Then you can call it using the following code:
string strStartPath = #"C:\Test\zip";
string strZipPath = #"C:\Test\output.zip";
ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create);
bool recursive = true;
foreach (var directoryPath in Directory.GetDirectories(strStartPath))
{
AddFolderToZip(archive, strStartPath, directoryPath, recursive);
}
archive.Dispose();
This code adds each directory it finds in a top level directory. And for each directory it finds, it will use recursion to add any subdirectories or files found within those.

FileNotFoundException While trying to copy the file from one directory to another

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)));

How to get path from different files in different directories?

I need to get path for each file in directories
eg: c:/a/b/c/1.jar and c:/dir/bin/2.jar must be saved as string
"c:/a/b/c/1.jar; c:/dir/bin/2.jar;..."
But the folders name may change in the future and I don't want to write this manually
Thanks for help
EDIT 1:
I've got the folder with few folders into. in each folder is files. I need to get all files directory in one string. eg: "dir1; dir2; dir3; ..."
but I can give only directory of main folder "c:/bin"
EDIT 2: Solved by Sayse
You can use Directory.EnumerateFiles
var allFiles = Directory.EnumerateFiles(sourceDirectory,
"*.*", //also can use "*.jar" here for just jar files
SearchOption.AllDirectories);
If you wish for all files to be in one long string then you can use
var fileString = string.Join(",", allFiles);
If its only directories you want
var allDirs = Directory.EnumerateDirectories("...",
"*",
SearchOption.AllDirectories);
var dirString = string.Join(";", allDirs);
class Program
{
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("C:\\");
FullDirList(di, "*");
Console.WriteLine("Done");
Console.Read();
}
static string myfolders = "";// Your string, which inclueds the folders like this: "c:/a/b/c; c:/dir/bin;..."
static string myfiles = ""; // Your string, which inclueds the file like this: "c:/a/b/c/1.jar; c:/dir/bin/2.jar;..."
static List<FileInfo> files = new List<FileInfo>(); // List that will hold the files and subfiles in path
static List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed
static void FullDirList(DirectoryInfo dir, string searchPattern)
{
// Console.WriteLine("Directory {0}", dir.FullName);
// list the files
try
{
foreach (FileInfo f in dir.GetFiles(searchPattern))
{
//Console.WriteLine("File {0}", f.FullName);
files.Add(f);
myfiles += f.FullName + ";";
}
}
catch
{
Console.WriteLine("Directory {0} \n could not be accessed!!!!", dir.FullName);
return; // We alredy got an error trying to access dir so dont try to access it again
}
// process each directory
// If I have been able to see the files in the directory I should also be able
// to look at its directories so I dont think I should place this in a try catch block
foreach (DirectoryInfo d in dir.GetDirectories())
{
myfolders += d.FullName + ";";
folders.Add(d);
FullDirList(d, searchPattern);
}
}
}
myfiles includes all files , like "C:\MyProgram1.exe;C:\MyFolder\MyProgram2.exe;C:\MyFolder2\MyProgram2.dll"
myfolder inclueds all folders, like "C:\MyFolder;C:\MyFolder2";

zip files with same names but different extensions using Ioniz.Zip DLL

I need help in writing a function which zips all files with same name but different extensions in a folder.I am using Ionic.Zip dll to achieve this.I am using .Net compact framework 2.0,VS2005. My code looks like this:
public void zipFiles()
{
string path = "somepath";
string[] fileNames = Directory.GetFiles(path);
Array.Sort(fileNames);//sort the filename in ascending order
string lastFileName = string.Empty;
string zipFileName = null;
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Files");
for (int i = 0; i < fileNames.Length; i++)
{
string baseFileName = fileNames[i];
if (baseFileName != lastFileName)
{
zipFileName=String.Format("Zip_{0}.zip",DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
zip.AddFile(baseFileName, "Files");
lastFileName = baseFileName;
}
}
zip.Save(zipFileName);
}
}
The problem:The folder will have 3 files with same name but their extensions will be different.Now,these files are being FTPed by a device so the filenames are auto-generated by it and I have no control over it.So,for example,there are 6 files in the folder:"ABC123.DON","ABC123.TGZ","ABC123.TSY","XYZ456.DON","XYZ456.TGZ","XYZ456.TSY". I have to zip the 3 files whose names are "ABC123" together and other 3 files with names "XYZ456".As I said,I wouldnt know the names of the files and my function has to run in background.My current code zips all the files in a single zip folder.
Can anyone please help me with this?
Try out the following code
string path = #"d:\test";
//First find all the unique file name i.e. ABC123 & XYZ456 as per your example
List<string> uniqueFiles=new List<string>();
foreach (string file in Directory.GetFiles(path))
{
if (!uniqueFiles.Contains(Path.GetFileNameWithoutExtension(file)))
uniqueFiles.Add(Path.GetFileNameWithoutExtension(file));
}
foreach (string file in uniqueFiles)
{
string[] filesToBeZipped = Directory.GetFiles(#"d:\test",string.Format("{0}.*",file));
//Zip all the files in filesToBeZipped
}

Categories

Resources