I am trying to change the extension of files within a folder to jpeg. I have used the below code to update the extension and it is working fine. But when i try to open each of the files, I am getting the error in photo viewer as "Windows photo viewer can't open this picture because the file appears to be damaged, corrupted or its too large."
DirectoryInfo d = new DirectoryInfo(#"E:\New folder (2)");
FileInfo[] Files = d.GetFiles();
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
string changed = Path.ChangeExtension(file.FullName, ".jpg");
File.WriteAllText(changed, "Changed file");
}
JPEG files are not text files. You need to Read and write bytes instead. ie:
DirectoryInfo d = new DirectoryInfo(#"E:\New folder (2)");
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
string changed = Path.ChangeExtension(file.FullName, "jpg");
File.Copy(file.FullName, changed);
}
Of course file themselves should be JPEG for this to work.
Related
I have 1 folder that contains many txt files. I want to zip them but separated.
Example:
In this folder I have A.txt, B.txt, C.txt.
I want to zip all the files but separated so the result will be A.zip, B.zip, C.zip.
string outputPath = "C:\\Users\\Desktop\\VA";
string path = outputPath + "\\VA_" + tglskrg;
foreach (string dirFile in Directory.GetDirectories(path))
{
foreach (string fileName in Directory.GetFiles(dirFile))
{
using (ZipFile zip = new ZipFile())
{
zip.UseUnicodeAsNecessary = true;
zip.AddFile(); //dont know what to put
zip.Save(); //dont know what to put
}
}
}
Any help will be appreciated.
I'm using dotnetzip (Ionic.zip) and C# Visual Studio Express 2010.
You could do that as follows:
foreach (string fileName in Directory.GetFiles(dirFile))
{
var zipFile = Path.Combine(outputPath, Path.ChangeExtension(fileName, ".zip"));
using (ZipFile zip = new ZipFile())
{
zip.AddFile(fileName); // add A.txt to the zip file
zip.Save(zipFile); // save as A.zip
}
}
This takes all the files found in the folder dirFile, and saves them under outputPath, with the same file name but replacing the extension with .zip.
I have automated a test script in selenium and c# whereby I click on an icon and it downloads a pdf file. I do not know the name of this file, so what I need is confirmations its been downloaded, the file name and then it deletes the file?
I have done some research and found some code but it doesn't work. Here is the latest code I have found but all it tells me in "files" is the number of pdf files in my directory.
string fileName = ConfigurationManager.AppSettings["Don't know file name"];
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, "Downloads");
DirectoryInfo downloadDir = new DirectoryInfo(pathDownload);
FileInfo[] files = downloadDir.GetFiles("*.pdf");
var file = files.Where(x => x.Name.Replace(" ", "") == fileName + ".pdf").FirstOrDefault();
fileName = file.FullName;
In case someone wants to know I have figured it out. So here is the code to confirm file has been downloaded and exists and then its deleted:
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string pathDownload = Path.Combine(pathUser, "Downloads");
DirectoryInfo downloadDir = new DirectoryInfo(pathDownload);
FileInfo[] files = downloadDir.GetFiles("*.pdf");
var filename = files[0].FullName;
string getFileName = Path.GetFileName(filename);
if (File.Exists(filename))
{
Console.WriteLine("The file has been downloaded successfully");
Console.WriteLine("The filename is: " + getFileName);
}
File.Delete(filename);
Hope it helps someone.
I need some help.
I just have this code right now. This code is working, but it's not enough.
My code;
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
foreach (FileInfo currentFile in infoFile)
{
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName))
{
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
foreach (ZipEntry currentZip in zipFile)
{ currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently); }
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
I want to extract all zip files to Application.StartupPath folder from _ZipFiles folder with all subdirectories.
Here is one example;
I have one zip folder. Name: _ZipFolder
Before the unzip process;
Application.StartupPath\_ZipFiles\startProgram.zip
Application.StartupPath\_ZipFiles\updateProgram.zip
Application.StartupPath\_ZipFiles\Pack\testDownload.zip
Application.StartupPath\_ZipFiles\Pack\Version\repo2.zip
Application.StartupPath\_ZipFiles\Pack\Version\newClass.zip
Application.StartupPath\_ZipFiles\Ack\Library\argSetup.zip
Application.StartupPath\_ZipFiles\Ack\learnMachine.zip
Application.StartupPath\_ZipFiles\Code\zipVersion4.zip
After the unzip process (I exactly want to this extract);
Application.StartupPath\startProgram.exe
Application.StartupPath\updateProgram.exe
Application.StartupPath\Pack\testDownload.exe
Application.StartupPath\Pack\Version\repo2.cs
Application.StartupPath\Pack\Version\newClass.cs
Application.StartupPath\Ack\Library\argSetup.exe
Application.StartupPath\Ack\learnMachine.pdf
Application.StartupPath\Code\zipVersion4.exe
All files needs move to Application.StartupPath from _ZipFiles folder with subdirectories.
How to make this? Please help me.
I hope you understand what I want. I'm sorry for my bad English.
Remove the zip folder name from the current file directory name when extracting
Based on current example where you have _ZipFiles folder
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
var zipFolderName = #"\_ZipFiles";
foreach (FileInfo currentFile in infoFile) {
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName)) {
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
var destination = currentFile.DirectoryName.Replace(zipFolderName, "");
foreach (ZipEntry currentZip in zipFile) {
currentZip.Extract(destination, ExtractExistingFileAction.OverwriteSilently);
}
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
If I understood you correctly, you want to extract all files to Application.StartupPath directory instead in subfolders.
Try to change:
currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently);
to
currentZip.Extract(Application.StartupPath, ExtractExistingFileAction.OverwriteSilently);
If Application.StartupPath isn't suitable, then maybe use AppDomain.CurrentDomain.BaseDirectory
I am trying to delete some files in a directory from a separate thread, but sometimes the delete doesn't work.
DirectoryInfo dirInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
FileInfo[] fileNames = dirInfo.GetFiles("*.*");
foreach (FileInfo fileName in fileNames)
{
string destinationFilename = cncDestinationDirectory + #"\" + dirInfo.Name + #"\" + fileName.Name;
if (File.Exists(destinationFilename))
File.Delete(destinationFilename);
File.Move(fileName.FullName, destinationFilename);
}
My goal is to move some files in a directory but, as I know the File.Move doesn't work if the destination file already exists. So, I check if the file exists and if it is true, I delete this file, then move to the original.
The File.Delete also cause a prematurely exit from the function.
The current directory is not the same folder as the executable is running because I set previously it into another folder.
How can I avoid this error? And still move the files in the destination directory?
The problem there is that the access to the file is denied because of the read only attribute of the file.
So, I set all my files attributes as normal as the follow:
DirectoryInfo dirInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
FileInfo[] fileNames = dirInfo.GetFiles("*.*");
foreach (FileInfo fileName in fileNames)
{
if (fileName.Extension == ".iso")
return;
string destinationFilename = cncDestinationDirectory + #"\" + dirInfo.Name + #"\" + fileName.Name;
fileName.Attributes = FileAttributes.Normal;
if (File.Exists(destinationFilename))
{
File.SetAttributes(destinationFilename, FileAttributes.Normal);
File.Delete(destinationFilename);
}
File.Move(fileName.FullName, destinationFilename);
}
You need to decide how to handle error cases like you suggest in your question. It's entirely possible that between checking the file exists and then deleting it, that the file has been opened by another process. You can catch an exception around the File.Delete and then not move the origin file if it throws, but you will end up with files that haven't moved. There's nothing you can do about it.
DirectoryInfo dirInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
FileInfo[] fileNames = dirInfo.GetFiles("*.*");
foreach (FileInfo fileName in fileNames)
{
string destinationFilename = cncDestinationDirectory + #"\" + dirInfo.Name + #"\" + fileName.Name;
try
{
if (File.Exists(destinationFilename))
File.Delete(destinationFilename);
File.Move(fileName.FullName, destinationFilename);
}
catch(IOException exception)
{
Console.WriteLine($"Can't move file { filename.FullName}");
}
}
I am able to zip files from a specific folder using ZipFile.CreateFromDirectory in the following test code (I only used this code to test how zipping works):
// Where the files are located
string strStartPath = txtTargetFolder.Text;
// Where the zip file will be placed
string strZipPath = #"C:\Users\smelmo\Desktop\testFinish\" + strFileNameRoot + "_" + txtDateRange1.Text.Replace(#"/", "_") + "_" + txtDateRange2.Text.Replace(#"/", "_") + ".zip";
ZipFile.CreateFromDirectory(strStartPath, strZipPath);
However, this zips together ALL of the contents in the folder. I am trying to zip together specific items in the folder using ZipArchive in the following code:
// Where the files are located
string strStartPath = txtTargetFolder.Text;
// Where the zip file will be placed
string strZipPath = #"C:\Users\smelmo\Desktop\testFinish\" + strFileNameRoot + "_" + txtDateRange1.Text.Replace(#"/", "_") + "_" + txtDateRange2.Text.Replace(#"/", "_") + ".zip";
using (ZipArchive archive = ZipFile.OpenRead(strStartPath))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (!(entry.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
{
entry.ExtractToFile(Path.Combine(strZipPath, entry.FullName));
}
}
}
It is giving the error at ZipFile.OpenRead(strStartPath). Why am I able to access the exact folder in the first block of code but not the second? Or is there an easier way to search through a folder and only zip specific items?
You are utilizing the Zip libraries wrong
Effectively you are trying to open a directory as if it were a zip file, then loop over the contents of that directory (which again is actually a zip file) and then attempting to extract each member into a different zip file
Here is a working example of what you have described you are trying to do:
string strStartPath = #"PATH TO FILES TO PUT IN ZIP FILE";
string strZipPath = #"PATH TO ZIP FILE";
if (File.Exists(strZipPath))
File.Delete(strZipPath);
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
foreach (FileInfo file in new DirectoryInfo(strStartPath).GetFiles())
{
if (!(file.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
{
archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), file.Name);
}
}
}
This will take all the root level contents of a folder and put it in the zip file. You will need to implement your own way of getting subfolders and their contents recursively, but that is beyond the scope of this question.
EDIT: Here is a working example with proper folder recursion to select all files even in subdirectories
public void ZipFolder()
{
string strStartPath = #"PATH TO FILES TO PUT IN ZIP FILE";
string strZipPath = #"PATH TO ZIP FILE";
if (File.Exists(strZipPath))
File.Delete(strZipPath);
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
foreach (FileInfo file in RecurseDirectory(strStartPath))
{
if (!(file.FullName.EndsWith(".TIF", StringComparison.OrdinalIgnoreCase)))
{
var destination = Path.Combine(file.DirectoryName, file.Name).Substring(strStartPath.Length + 1);
archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), destination);
}
}
}
}
public IEnumerable<FileInfo> RecurseDirectory(string path, List<FileInfo> currentData = null)
{
if (currentData == null)
currentData = new List<FileInfo>();
var directory = new DirectoryInfo(path);
foreach (var file in directory.GetFiles())
currentData.Add(file);
foreach (var d in directory.GetDirectories())
RecurseDirectory(d.FullName, currentData);
return currentData;
}