how to make rar file of full folder using c# - c#

I have a procedure for making .rar file.
Code
public static void RarFilesT(string rarPackagePath, Dictionary<int, string> accFiles)
{
string[] files = new string[accFiles.Count];
int i = 0;
foreach (var fList_item in accFiles)
{
files[i] = "\"" + fList_item.Value;
i++;
}
string fileList = string.Join("\" ", files);
fileList += "\"";
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("A {0} {1} -ep",
String.Format("\"{0}\"", rarPackagePath),
fileList);
sdp.ErrorDialog = true;
sdp.UseShellExecute = true;
sdp.Arguments = cmdArgs;
sdp.FileName = rarPath;//Winrar.exe path
sdp.CreateNoWindow = false;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
}
This producer needs an string array of file list for making rar file.
Can any one tell me how can i make rar of a complete folder with sub folders and files.
Sorry 1 mistake and i also need selected extension files from given folder.

Updated function
/// <summary>
/// Package files. (Build Rar File)
/// </summary>
/// <param name="rarPackagePath">Rar File Path</param>
/// <param name="accFiles">List Of Files To be Package</param>
public static string RarFiles(string rarPackagePath,
Dictionary<int, string> accFiles)
{
string error = "";
try
{
string[] files = new string[accFiles.Count];
int i = 0;
foreach (var fList_item in accFiles)
{
files[i] = "\"" + fList_item.Value;
i++;
}
string fileList = string.Join("\" ", files);
fileList += "\"";
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("A {0} {1} -ep1 -r",
String.Format("\"{0}\"", rarPackagePath),
fileList);
sdp.ErrorDialog = false;
sdp.UseShellExecute = true;
sdp.Arguments = cmdArgs;
sdp.FileName = winrarPath;//Winrar.exe path
sdp.CreateNoWindow = false;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
error = "OK";
}
catch (Exception ex)
{
error = ex.Message;
}
return error;
}
For this u can make rar with full folder path.
-r argument can recursive folder and files.
Thanks to bystander.
And also u can specify extension for packaging.
Ex.
string rarPackage = "E:/Backup.rar";
Dictionary<int, string> accFiles = new Dictionary<int, string>();
accFiles.Add(1, "D://*.txt");
accFiles.Add(2, "D://*.html");
accFiles.Add(3, "D://*.jpg");
RarFiles(rarPackage, accFiles);
Un-Rar
public static void UnrarFiles(string rarPackagePath, string dir)
{
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("X {0} * {1}",
String.Format("\"{0}\"", rarPackagePath),
String.Format("\"{0}\"", dir));
sdp.Arguments = cmdArgs;
sdp.ErrorDialog = true;
sdp.UseShellExecute = true;
sdp.CreateNoWindow = false;
sdp.FileName = rarPath;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
}

-r argument can recursive folder and files..
so you add "-r" to
string cmdArgs = string.Format("A {0} {1} -ep -r",
String.Format("\"{0}\"", rarPackagePath),
fileList);

Ashish, Thanks for posting this; it's very helpful to me, as I've been told at the last moment that some files I have to FTP are supposed to be RARed first.
But I'm curious -- why is accFiles a dictionary, rather than a string[] or a Collection? Microsoft suggests not to pass dictionaries in public APIs: http://msdn.microsoft.com/en-us/library/dn169389(v=vs.110).aspx
Also, using a StringBuilder would clean up building fileList. I'd suggest this:
public static string RarFiles(string rarPackagePath,
Collection<string> accFiles)
{
string error = "";
try
{
StringBuilder fileListBuilder = new StringBuilder();
foreach (var fList_item in accFiles)
{
fileListBuilder.Append("\"" + fList_item + "\" ");
}
string fileList = fileListBuilder.ToString();
... (no change from this point on)
}
Again, thanks -- it's really been very helpful to me. I hope my suggestions are helpful to you, as well.

Related

Trying to run same command in command prompt not working

I am making a program that seeks out secured PDFs in a folder and converting them to PNG files using ImageMagick. Below is my code.
string WorkDir = #"C:\Users\rwong\Desktop\TestFiles";
Directory.SetCurrentDirectory(WorkDir);
String[] SubWorkDir = Directory.GetDirectories(WorkDir);
foreach (string subdir in SubWorkDir)
{
string[] filelist = Directory.GetFiles(subdir);
for(int f = 0; f < filelist.Length; f++)
{
if (filelist[f].ToLower().EndsWith(".pdf") || filelist[f].EndsWith(".PDF"))
{
PDFReader reader = new Pdfreader(filelist[f]);
bool PDFCheck = reader.IsOpenedWithFullPermissions;
reader.CLose();
if(PDFCheck)
{
//do nothing
}
else
{
string PNGPath = Path.ChangeExtension(filelistf], ".png");
string PDFfile = '"' + filelist[f] + '"';
string PNGfile = '"' + PNGPath + '"';
string arguments = string.Format("{0} {1}", PDFfile, PNGfile);
ProcessStartInfo startInfo = new ProcessStartInfo(#"C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe");
startInfo.Arguments = arguments;
Process.Start(startInfo);
}
}
}
I have ran the raw command in command prompt and it worked so the command isn't the issue. Sample command below
"C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe" "C:\Users\rwong\Desktop\TestFiles\Test_File File_10.PDF" "C:\Users\rwong\Desktop\TestFiles\Test_File File_10.png"
I looked around SO and there has been hints that spaces in my variable can cause an issue, but most of those threads talk about hardcoding the argument names and they only talk about 1 argument. I thought adding double quotes to each variable would solve the issue but it didn't. I also read that using ProcessStartInfo would have helped but again, no dice. I'm going to guess it is the way I formatted the 2 arguments and how I call the command, or I am using ProcessStartInto wrong. Any thoughts?
EDIT: Based on the comments below I did the extra testing testing by waiting for the command window to exit and I found the following error.
Side note: I wouldn't want to use GhostScript just yet because I feel like I am really close to an answer using ImageMagick.
Solution:
string PNGPath = Path.ChangeExtension(Loan_list[f], ".png");
string PDFfile = PNGPath.Replace("png", "pdf");
string PNGfile = PNGPath;
Process process = new Process();
process.StartInfo.FileName = #"C:\Program Files\ImageMagick-6.9.2 Q16\convert.exe";
process.StartInfo.Arguments = "\"" + PDFfile + "\"" +" \"" + PNGPath +"\""; // Note the /c command (*)
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
string err = process.StandardError.ReadToEnd();
Console.WriteLine(err);
process.WaitForExit();
It didn't like the way I was formatting the argument string.
This would help you to run you command in c# and also you can get the result of the Console in your C#.
string WorkDir = #"C:\Users\rwong\Desktop\TestFiles";
Directory.SetCurrentDirectory(WorkDir);
String[] SubWorkDir = Directory.GetDirectories(WorkDir);
foreach (string subdir in SubWorkDir)
{
string[] filelist = Directory.GetFiles(subdir);
for(int f = 0; f < filelist.Length; f++)
{
if (filelist[f].ToLower().EndsWith(".pdf") || filelist[f].EndsWith(".PDF"))
{
PDFReader reader = new Pdfreader(filelist[f]);
bool PDFCheck = reader.IsOpenedWithFullPermissions;
reader.CLose()l
if(!PDFCheck)
{
string PNGPath = Path.ChangeExtension(filelistf], ".png");
string PDFfile = '"' + filelist[f] + '"';
string PNGfile = '"' + PNGPath + '"';
string arguments = string.Format("{0} {1}", PDFfile, PNGfile);
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.EnableRaisingEvents = true;
p.StartInfo.CreateNoWindow = true;
p.startInfo.FileName = "C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe";
p.startInfo.Arguments = arguments;
p.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
//You can receive the output provided by the Command prompt in Process_OutputDataReceived
p.Start();
}
}
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
string s = e.Data.ToString();
s = s.Replace("\0", string.Empty);
//Show s
Console.WriteLine(s);
}
}

nAudio FadeInOutSampleProvider not working

I'm writing a program which will take a series of .wav files from a folder created by another application, trims a specified amount of time from the start and end of each sample and copies the result of that action to a temporary folder. From there, I want to take each of the files and apply a small amount of fading to the end of the files as to make the transitions between files smoother (each file will be merged together afterwards), and output the results of that operation to another temporary folder, where the program will merge the files in that folder to create the final output. Unfortunately, I can't get FadeInOutSampleProvider to work.
foreach (string file in files) {
try {
byte[] buffer = new byte[1024];
AudioFileReader afr = new AudioFileReader(tempfile2);
FadeInOutSampleProvider fade = new FadeInOutSampleProvider(afr);
fade.BeginFadeOut(notes[run2].Length - 100);
var stwp = new NAudio.Wave.SampleProviders.SampleToWaveProvider(fade);
WaveFileWriter.CreateWaveFile(tempfile, stwp);
run2++;
}
catch (Exception) { }
}
EDIT:
Here's more code:
public void PlaybackTemp(string tempDir, Sheet playbackSheet) {
string[] files = Directory.GetFiles(tempDir);
string tempdir = "";
// Generate trimmed files ready for splicing
tempdir = GenEditedFiles(files, playbackSheet.notes);
// Show the output in explorer if debug mode is on
if (debug) {
Process p = new Process();
p.StartInfo.FileName = tempdir;
p.Start();
}
// Splice the files
ConcatenateWav(tempdir + "\\render.wav", Directory.GetFiles(tempdir));
// Play back resulting file
new System.Media.SoundPlayer(tempdir + "\\render.wav").Play();
}
private string GenEditedFiles(string[] files, List<Note> notes) {
string tempdir = FluidSys.FluidSys.CreateTempDir();
string tempdir2 = FluidSys.FluidSys.CreateTempDir();
string tempfile = "";
string tempfile2 = "";
int run = 0;
int run2 = 0;
// Trim each note
foreach (string file in files) {
tempfile = tempdir + "\\" + run.ToString() + ".wav";
tempfile2 = tempdir + "\\" + run.ToString() + "0.wav";
WavFileUtils.TrimWavFile(file, tempfile2, TimeSpan.FromMilliseconds(notes[run].VoiceProperties.Start),
TimeSpan.FromMilliseconds(notes[run].VoiceProperties.End));
run++;
}
foreach (string file in files) {
try {
byte[] buffer = new byte[1024];
AudioFileReader afr = new AudioFileReader(tempfile2);
FadeInOutSampleProvider fade = new FadeInOutSampleProvider(afr);
fade.BeginFadeOut(notes[run2].Length - 10);
var stwp = new NAudio.Wave.SampleProviders.SampleToWaveProvider(fade);
WaveFileWriter.CreateWaveFile(tempfile, stwp);
run2++;
}
catch (Exception) { }
}
return tempdir;
}

Unzip a file in c# using 7z.exe

I'm trying to unzip a file from a winform application.
I'm using this code :
string dezarhiverPath = #AppDomain.CurrentDomain.BaseDirectory + "\\7z.exe";
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = dezarhiverPath;
pro.Arguments = #" e c:\TEST.ZIP";
Process x = Process.Start(pro);
x.WaitForExit();
The code doesn't return error but doesn't anything.
I tried this command also from cmd :
K:\>"C:\Test\7z.exe" e "c:\TEST.ZIP"
but in cmd ,I receive this error message :
7-Zip cannot find the code that works with archives.
Can somebody help me to unzip some files from c# ?
Thanks!
Why would you bother trying to use the 7z.exe application externally? That is a very kludgy way of doing it. Instead use one of the many libraries at your disposal.
If this is a new application, and you are targeting .NET 4.5, The new System.IO.Compression namespace has a ZipFile class.
Alternatively, SharpZipLib is a GPL library for file compression in .NET. There are online samples.
Also available is DotNetZip which is Ms-PL licensed.
Hey use this code below , you must have 7zip application in your system .
public void ExtractFile(string source, string destination)
{
string zPath = #"C:\Program Files\7-Zip\7zG.exe";// change the path and give yours
try
{
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + source + "\" -o" + destination;
Process x = Process.Start(pro);
x.WaitForExit();
}
catch (System.Exception Ex) {
//DO logic here
}
}
to create :
public void CreateZip()
{
string sourceName = #"d:\a\example.txt";
string targetName = #"d:\a\123.zip";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"C:\Program Files\7-Zip\7zG.exe";
p.Arguments = "a -tgzip \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
}
Refer Following Code:
using System.IO.Compression;
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
Referance Link:
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/849c4969-24b1-4650-88a5-5169727e527f/
You can use SevenZipSharp library
using (var input = File.OpenRead(lstFiles[0]))
{
using (var ds = new SevenZipExtractor(input))
{
//ds.ExtractionFinished += DsOnExtractionFinished;
var mem = new MemoryStream();
ds.ExtractFile(0, mem);
using (var sr = new StreamReader(mem))
{
var iCount = 0;
String line;
mem.Position = 0;
while ((line = sr.ReadLine()) != null && iCount < 100)
{
iCount++;
LstOutput.Items.Add(line);
}
}
}
}
Try this
string fileZip = #"c:\example\result.zip";
string fileZipPathExtactx= #"c:\example\";
ProcessStartInfo p = new ProcessStartInfo();
p.WindowStyle = ProcessWindowStyle.Hidden;
p.FileName = dezarhiverPath ;
p.Arguments = "x \"" + fileZip + "\" -o" + fileZipPathExtact;
Process x = Process.Start(p);
x.WaitForExit();
This maybe can help you.
//You must create an empty folder to remove.
string tempDirectoryPath = #"C:\Users\HOPE\Desktop\Test Folder\zipfolder";
string zipFilePath = #"C:\Users\HOPE\Desktop\7za920.zip";
Directory.CreateDirectory(tempDirectoryPath);
ZipFile.ExtractToDirectory(zipFilePath, tempDirectoryPath);

How to specify multiple file extension for making rar of a folder?

I'm using c# code for making .rar file of a folder.
Code
string zipFileToWrite, folderPath;
zipFileToWrite = #"D:\jack.zip";
folderPath = #"D:\New folder";
System.Diagnostics.Process MyProcess = new System.Diagnostics.Process();
MyProcess.StartInfo.WorkingDirectory = #"D:\NetworkPathChecking\FileBackup\FileBackup\bin\Debug\App_Files\";
MyProcess.StartInfo.FileName = "winrar.exe";
MyProcess.StartInfo.Arguments = "a -r " + "\"" + zipFileToWrite + "\"" + " " + "\"" + folderPath + "\"";
MyProcess.Start();
MyProcess.WaitForExit();
Now I need to specify multipule extension as filter for files to make .rar from folder.
How can I do this?
Problem is solved by using files list with *.FileExtension.
Procedure
public static string RarFilesT(string rarPackagePath, Dictionary<int, string> accFiles)
{
string error = "";
try
{
string[] files = new string[accFiles.Count];
int i = 0;
foreach (var fList_item in accFiles)
{
files[i] = "\"" + fList_item.Value;
i++;
}
string fileList = string.Join("\" ", files);
fileList += "\"";
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("A {0} {1} -ep1 -r",
String.Format("\"{0}\"", rarPackagePath),
fileList);
sdp.ErrorDialog = true;
sdp.UseShellExecute = true;
sdp.Arguments = cmdArgs;
sdp.FileName = rarPath;//Winrar.exe path
sdp.CreateNoWindow = false;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
error = "OK";
}
catch (Exception ex)
{
error = ex.Message;
}
return error;
}
Call Procedure
private void btnSave_Click(object sender, EventArgs e)
{
Dictionary<int, string> accFiles = new Dictionary<int, string>();
accFiles.Add(1, #"D:\New folder\New folder\*.txt");
accFiles.Add(2, #"D:\New folder\*.html");
RarFilesT(#"D:\test.rar",accFiles );
}
Now this procedure works fine.It takes full backup of folder with selected extension.

how to zip the file using ionic library

I have done this one for backup my database
its working fine ....
private void backupDatabase()
{
txtbackup.AppendText("Starting Backup...");
Process sd = null;
const string backupcmd = #"C:\wamp\www\access\mysqldump.exe";
string filepath = #"C:\folder\Access\";
string dbHost = "local";
string dbuser = "root";
string dbName = "access";
string backupName = "Backup.sql";
ProcessStartInfo r1 = new ProcessStartInfo(backupcmd, string.Format("-h {0} -u {1} {2} -r {3}", dbHost, dbuser, dbName, backupName));
r1.CreateNoWindow = true;
r1.WorkingDirectory = filepath;
r1.UseShellExecute = false;
r1.WindowStyle = ProcessWindowStyle.Minimized;
r1.RedirectStandardInput = false;
sd = Process.Start(r1);
sd.WaitForExit();
if (!sd.HasExited)
{
sd.Close();
}
sd.Dispose();
r1 = null;
sd = null;
txtbackup.Clear();
txtbackup.AppendText("Backup is Finished");
}
its working fine ...but i want to store the backup.sql as a zip file in this path
#"C:\folder\Access\";
i have got this library Ionic.Zip.Reduced but i dont know how to zip the file and stored in the given path....
The library is pretty simple to use :
using (var zip = new ZipFile())
{
zip.AddFile("Backup.sql");
zip.Save(#"C:\folder\Access\"Backup.zip");
}
And even their homepage contains samples good enough for your use.
You should use this compression library or this one may be an option?

Categories