Open and print PDF files - c#

I'd like to open and print all PDF files located in a given folder. The files are named according to the following pattern:
NameOfThePrinter_Timestamp.pdf
Now I want to print those files using the corresponding printer:
static void Main(string[] args)
{
string pdf = #"C:\PathToFolder";
if (Directory.GetFiles(pdf).Length > 0)
{
string[] files = Directory.GetFiles(pdf);
var adobe = Registry.LocalMachine.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("App Paths").OpenSubKey("AcroRd32.exe");
var path = adobe.GetValue("");
string acrobat = path.ToString();
for (int i = 0; i < files.Length; i++)
{
Process process = new Process();
process.StartInfo.FileName = acrobat;
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "/p /s /h \"" + files[i] + "\"";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
DateTime start = DateTime.Now;
IntPtr handle = IntPtr.Zero;
while (handle == IntPtr.Zero && DateTime.Now - start <= TimeSpan.FromSeconds(2))
{
try
{
System.Threading.Thread.Sleep(50);
handle = process.MainWindowHandle;
} catch (Exception) { }
}
foreach (String verb in process.StartInfo.Verbs)
{
// Display the possible verbs.
Console.WriteLine(" {0}. {1}", i.ToString(), verb);
i++;
}
System.Threading.Thread.Sleep(10000);
Console.Out.WriteLine("File: " + files[i] + " is printing!");
process.Kill();
}
foreach (string str in files)
{
File.Delete(str);
}
Console.Out.WriteLine("Files are deleted!");
}
}
My question is: How can I pass the printer name as parameter?
Here I've tried something, but it either throws and error or prints to the default printer:
process.StartInfo.Arguments = "/p /s /h \"" + files[i] + "\"";

You can use Ghostscript to send the PDF document to the printer.
Here you can find a sample how to send the PDF document to printer: How to print PDF on default network printer using GhostScript (gswin32c.exe) shell command
And here you can find Ghostscript wrapper for .NET if you want to control Ghostscript directly without calling .exe file: http://ghostscriptnet.codeplex.com

function printDisclosureDocument() {
var doc = document.getElementById('pdfDocument');
if (doc == 'undefined' || doc == null) {
var pdfbox = document.createElement('embed');
pdfbox.type = 'application/pdf';
pdfbox.src = 'ShowPDF.aspx?refid=' + $('#MainContent_hdnRefId').val();
pdfbox.width = '1';
pdfbox.height = '1';
pdfbox.id = 'pdfDocument';
document.body.appendChild(pdfbox);
}
if (doc != null && doc != 'undefined') {
//Wait until PDF is ready to print
if (typeof doc.print === 'undefined') {
setTimeout(function () { printDisclosureDocument(); }, 500);
} else {
doc.print();
}
}
else {
setTimeout(function () { printDisclosureDocument(); }, 500);
}
}

Related

Download you tube video using c#?

I am trying to download you tube video using c# code but i am not getting proper code. I have searched many link but din't get any proper links and code.
I want to download the you tube video in my local folder with c# code. I have tried one link but that code just getting null video in my local folder so any one have the idea how can do that.
Below is the code i have tried so far.
var VedioUrl = "https://www.youtube.com/embed/" + objYouTube.VideoID + ".mp4";
WebRequest MyRequest = HttpWebRequest.Create(VedioUrl);
WebResponse MyResponse = MyRequest.GetResponse();
string RealURL = MyResponse.ResponseUri.ToString();
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RealURL);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream receiveStream = myHttpWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(receiveStream, encode);
StreamWriter writer = new StreamWriter(Server.MapPath("~/youtube/" + objYouTube.VideoID + ".mp4"), true);
writer.Write(readStream.ReadToEnd());
writer.Close();
so here is my video url which i am trying to download : "https://www.youtube.com/embed/UCsiNPbLbwZk43FOCRrdKBlA.mp4"
I have find the solution for download you tube videos using c# code.
First need install the "libvideo" on NuGet package manager console in visual studio.
Here Fire this command on package manger console :
Install-Package VideoLibrary
First add this namespace on top in your controller :
using VideoLibrary;
Now here just write just code and pass the url link :
var VedioUrl = "https://www.youtube.com/embed/" + objYouTube.VideoID + ".mp4";
var youTube = YouTube.Default;
var video = youTube.GetVideo(VedioUrl);
System.IO.File.WriteAllBytes(Server.MapPath("~/youtube/" + video.FullName + ".mp4"), video.GetBytes());
You can embed youtube-dl in your app.
It provides extensive Youtube download options.
Basically, you do something like this.
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace MyProcessSample
{
class MyProcess
{
public static void Main()
{
Process myProcess = new Process();
try
{
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = #"yourpath\youtube-dl.exe";
myProcess.StartInfo.CreateNoWindow = false;
myProcess.StartInfo.Arguments = "https://www.youtube.com/watch?v=KFqrp4KSxio";
myProcess.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
You can use this C# wapper for youtube-dl.
You can extend it to suite your needs.
Process Class
For a more up to date solution, check out YoutubeExplode. It offers rich API to query and download Youtube videos and, unlike other libraries, is still actively maintained.
after install the "libvideo" on NuGet package manager console in visual studio.
and download ffmpeg for merge audio and video for best output .
follow this code :
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using VideoLibrary;
namespace you_tube_download
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("write url video : ");
string url = Console.ReadLine();
string information = "";
var videos = YouTube.Default.GetAllVideos(url);
int hightaudio = 1;
int hightvideo = 1;
Console.WriteLine("\nlist all format \n");
foreach (var item in videos)//write all file on this url
{
Console.WriteLine(item.Resolution+","+item.Format + "," + item.AudioFormat + "," + item.AudioBitrate + "," + item.ContentLength + "," + item.AdaptiveKind);
if (item.AdaptiveKind.ToString() == "Audio" && item.AudioBitrate > hightaudio)
{
hightaudio = item.AudioBitrate;
information = item.AudioFormat + "," + item.AudioBitrate+","+item.ContentLength;
}
if (item.Resolution > hightvideo)
{
hightvideo = item.Resolution;
}
}
Console.WriteLine("\ndownload high video resolotion {0} and high audio bitrate {1}",hightvideo,hightaudio);
string[] split = information.Split(',');
foreach (var item in videos)//download audio
{
if (split[0]== item.AudioFormat.ToString() && split[1] == item.AudioBitrate.ToString() && split[2] == item.ContentLength.ToString())
{
Console.WriteLine("\ndownload audio with bitrate {0} and size {1}MB",item.AudioBitrate, Math.Round((double)item.ContentLength / 1000000, 2));
downloadbest(item, Directory.GetCurrentDirectory() + "\\file123456798.mp3");
Console.Write("end\n");
}
}
foreach (var item in videos)//download video
{
if (item.Resolution==hightvideo)
{
Console.WriteLine("\ndownload video with Resolution {0} and size {1}MB", item.Resolution, Math.Round((double)item.ContentLength/1000000,2));
downloadbest(item, Directory.GetCurrentDirectory() + "\\file123456798.mp4");
Console.Write("end\n");
break;
}
}
Console.WriteLine("wait for marge");
combine();
File.Delete(Directory.GetCurrentDirectory() + "\\file123456798.mp3");
File.Delete(Directory.GetCurrentDirectory() + "\\file123456798.mp4");
Console.WriteLine("press any key to continue...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("\n\n\n\n" + ex);
Console.ReadKey();
}
Process.Start(Directory.GetCurrentDirectory());
}
static void combine()
{
Process p = new Process();
p.StartInfo.FileName = "ffmpeg.exe";
p.StartInfo.Arguments = "-i \"" + Directory.GetCurrentDirectory() + "\\file123456798.mp4\" -i \"" + Directory.GetCurrentDirectory() + "\\file123456798.mp3\" -preset veryfast \"" + Directory.GetCurrentDirectory() + "\\final.mp4\"";
p.Start();
p.WaitForExit();
}
static void downloadbest(YouTubeVideo y, string patch)
{
int total = 0;
FileStream fs =null;
Stream streamweb = null;
WebResponse w_response = null;
try
{
WebRequest w_request = WebRequest.Create(y.Uri);
if (w_request != null)
{
w_response = w_request.GetResponse();
if (w_response != null)
{
fs = new FileStream(patch, FileMode.Create);
byte[] buffer = new byte[128*1024];
int bytesRead = 0;
streamweb = w_response.GetResponseStream();
Console.WriteLine("Download Started");
do
{
bytesRead = streamweb.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, bytesRead);
total += bytesRead;
Console.Write($"\rDownloading ({Math.Round(((double)total/(int)y.ContentLength) * 100, 2)}%) {total}/{y.ContentLength} ");
} while (bytesRead > 0);
Console.WriteLine("\nDownload Complete");
}
}
}
catch (Exception ex)
{
Console.WriteLine("\n\n\n\n" + ex);
Console.ReadKey();
Process.Start(Directory.GetCurrentDirectory());
}
finally
{
if (w_response != null) w_response.Close();
if (fs != null) fs.Close();
if (streamweb != null) streamweb.Close();
}
}
}
}

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

How to print a PDF file from code? [duplicate]

This question already has answers here:
How can I send a file document to the printer and have it print?
(12 answers)
Windows 8 blows error on c# process for printing pdf file, how?
(1 answer)
Closed 9 years ago.
I've been developing an application in visual c# which needs to print an existing pdf file at the press of a button.
I've been using the System.Diagnostics.Process method to print but it fails to work as desired in a Windows 8 environment as the "Printto" command doesn't seem to work there.
I would like to use an alternative such as possibly the System.Drawing.Printing.PrintDocument which had an example that works with text files but when I tried with a pdf it was printing random characters instead.
My google searches for such seem to come up empty or I'm not entering the right keywords, but I need a solution which not only prints pdf to target printer but can determine if the printer is ready, offline or out of paper as well as an error catch.
Please advise as I'm also willing to look at any SDK or third party routes recommendable.
edit: added code snippet I'm currently using:
string defFile = (Path.Combine(GlobalVars.pdfPath, tkt_no + "_DEF.pdf"));
string rwPrinter = "";
if (GlobalVars.useDefaultPrinter == false)
{
foreach (string strPrinter in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
if (strPrinter.StartsWith("ZDesigner"))
{
rwPrinter = strPrinter;
break;
}
}
}
if (jobdo.Equals("print"))
{
Process process = new Process();
//process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.FileName = defFile;
if (rwPrinter.Length > 0)
{
process.StartInfo.Verb = "printto";
//process.StartInfo.Verb = (Path.Combine(System.Windows.Forms.Application.StartupPath, "printto.exe"));
process.StartInfo.Arguments = "\"" + rwPrinter + "\"";
}
else
{
process.StartInfo.Verb = "print";
}
try
{
process.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
process.WaitForInputIdle();
//while (process.MainWindowHandle == IntPtr.Zero)
//{
// Thread.Sleep(20);
// process.Refresh();
//}
Thread.Sleep(7000);
try
{
process.Kill();
}
catch { }
// close any occurrences of Adobe Reader that may not close through a citrix environment regardless
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
if (p.ProcessName.Equals("AcroRd32"))
{
ObjectQuery sq = new ObjectQuery
("Select * from Win32_Process where ProcessID = '" + p.Id + "'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(sq);
foreach (ManagementObject oReturn in searcher.Get())
{
string[] o = new string[2];
oReturn.InvokeMethod("GetOwner", (object[])o);
if(o[0] != null)
if(o[0].Equals(System.Environment.UserName))
p.Kill();
}
}
}
if (rwPrinter == "")
{
rwPrinter = "the default printer";
}
else
MessageBox.Show("Ticket " + tkt_no + " was printed to " + rwPrinter + ".");
}
Please see this, using iTextSharp library you can easily create PDF file:
http://sourceforge.net/projects/itextsharp/

extract ISO with winrar automatically with c# or batch

I'm trying to extract an ISO to a folder with the same name without .iso on the end.
I'm having a problem with winrar as it will not start the extract when I start up with the seach starting in the folder with the ISO.
UPDATED with answer code
private void ExtractISO(string toExtract, string folderName)
{
// reads the ISO
CDReader Reader = new CDReader(File.Open(toExtract, FileMode.Open), true);
// passes the root directory the folder name and the folder to extract
ExtractDirectory(Reader.Root, folderName /*+ Path.GetFileNameWithoutExtension(toExtract)*/ + "\\", "");
// clears reader and frees memory
Reader.Dispose();
}
private void ExtractDirectory(DiscDirectoryInfo Dinfo, string RootPath, string PathinISO)
{
if (!string.IsNullOrWhiteSpace(PathinISO))
{
PathinISO += "\\" + Dinfo.Name;
}
RootPath += "\\" + Dinfo.Name;
AppendDirectory(RootPath);
foreach (DiscDirectoryInfo dinfo in Dinfo.GetDirectories())
{
ExtractDirectory(dinfo, RootPath, PathinISO);
}
foreach (DiscFileInfo finfo in Dinfo.GetFiles())
{
using (Stream FileStr = finfo.OpenRead())
{
using (FileStream Fs = File.Create(RootPath + "\\" + finfo.Name)) // Here you can Set the BufferSize Also e.g. File.Create(RootPath + "\\" + finfo.Name, 4 * 1024)
{
FileStr.CopyTo(Fs, 4 * 1024); // Buffer Size is 4 * 1024 but you can modify it in your code as per your need
}
}
}
}
static void AppendDirectory(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (DirectoryNotFoundException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
catch (PathTooLongException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
}
The user selects the folder to extract (.ISO) toExtract. I then use it in the Process.Start() in the background worker. That just seems to open the mounting software and doesn't extract the ISO to the desired folder name.
Thanks in advance for your help.
Or if anyone could give me a batch to extract the ISO instead and to call it from c# passing toExtract and the folder name that would be helpful too.
Thanks
If external Class Libraries are OK!
Then use SevenZipSharp or .NET DiscUtils to extract ISO's...
These two ClassLibraries can manage ISO and Extract them!
For DiscUtils you can find some codes for ISO Management [CDReader Class] at the Link I provided.
But For SevenZipSharp, Please Explore the ClassLibrary source and find the Code to Extract or Google to find it!
To get the Name of the folder just use Path.GetFileNameWithoutExtension((string)ISOFileName) which will return "ISOFile" for an iso named "ISOFile.iso". And then you can use it with your desired path.
UPDATE
Code To Extract ISO Image with DiscUtils :
using DiscUtils;
using DiscUtils.Iso9660;
void ExtractISO(string ISOName, string ExtractionPath)
{
using (FileStream ISOStream = File.Open(ISOName, FileMode.Open))
{
CDReader Reader = new CDReader(ISOStream, true, true);
ExtractDirectory(Reader.Root, ExtractionPath + Path.GetFileNameWithoutExtension(ISOName) + "\\", "");
Reader.Dispose();
}
}
void ExtractDirectory(DiscDirectoryInfo Dinfo, string RootPath, string PathinISO)
{
if (!string.IsNullOrWhiteSpace(PathinISO))
{
PathinISO += "\\" + Dinfo.Name;
}
RootPath += "\\" + Dinfo.Name;
AppendDirectory(RootPath);
foreach (DiscDirectoryInfo dinfo in Dinfo.GetDirectories())
{
ExtractDirectory(dinfo, RootPath, PathinISO);
}
foreach (DiscFileInfo finfo in Dinfo.GetFiles())
{
using (Stream FileStr = finfo.OpenRead())
{
using (FileStream Fs = File.Create(RootPath + "\\" + finfo.Name)) // Here you can Set the BufferSize Also e.g. File.Create(RootPath + "\\" + finfo.Name, 4 * 1024)
{
FileStr.CopyTo(Fs, 4 * 1024); // Buffer Size is 4 * 1024 but you can modify it in your code as per your need
}
}
}
}
static void AppendDirectory(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (DirectoryNotFoundException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
catch (PathTooLongException Exx)
{
AppendDirectory(Path.GetDirectoryName(path));
}
}
Use It with Like This :
ExtractISO(ISOFileName, Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\");
Working! Tested By Me!
And Of Course You can always add more Optimization to the code...
This Code is Just a Basic One!
For UDF or for making Windows ISO Files after servicing(DISM) with out needs the above accepted answer is not working for me so i tried this working method with DiscUtils
using DiscUtils;
public static void ReadIsoFile(string sIsoFile, string sDestinationRootPath)
{
Stream streamIsoFile = null;
try
{
streamIsoFile = new FileStream(sIsoFile, FileMode.Open);
DiscUtils.FileSystemInfo[] fsia = FileSystemManager.DetectDefaultFileSystems(streamIsoFile);
if (fsia.Length < 1)
{
MessageBox.Show("No valid disc file system detected.");
}
else
{
DiscFileSystem dfs = fsia[0].Open(streamIsoFile);
ReadIsoFolder(dfs, #"", sDestinationRootPath);
return;
}
}
finally
{
if (streamIsoFile != null)
{
streamIsoFile.Close();
}
}
}
public static void ReadIsoFolder(DiscFileSystem cdReader, string sIsoPath, string sDestinationRootPath)
{
try
{
string[] saFiles = cdReader.GetFiles(sIsoPath);
foreach (string sFile in saFiles)
{
DiscFileInfo dfiIso = cdReader.GetFileInfo(sFile);
string sDestinationPath = Path.Combine(sDestinationRootPath, dfiIso.DirectoryName.Substring(0, dfiIso.DirectoryName.Length - 1));
if (!Directory.Exists(sDestinationPath))
{
Directory.CreateDirectory(sDestinationPath);
}
string sDestinationFile = Path.Combine(sDestinationPath, dfiIso.Name);
SparseStream streamIsoFile = cdReader.OpenFile(sFile, FileMode.Open);
FileStream fsDest = new FileStream(sDestinationFile, FileMode.Create);
byte[] baData = new byte[0x4000];
while (true)
{
int nReadCount = streamIsoFile.Read(baData, 0, baData.Length);
if (nReadCount < 1)
{
break;
}
else
{
fsDest.Write(baData, 0, nReadCount);
}
}
streamIsoFile.Close();
fsDest.Close();
}
string[] saDirectories = cdReader.GetDirectories(sIsoPath);
foreach (string sDirectory in saDirectories)
{
ReadIsoFolder(cdReader, sDirectory, sDestinationRootPath);
}
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
it has extracted from a application source ISOReader but modified for my requirements
total source is available at http://www.java2s.com/Open-Source/CSharp_Free_CodeDownload/i/isoreader.zip
Try this:
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Process.Start("Winrar.exe", string.Format("x {0} {1}",
Desktop + "\\test.rar",
Desktop + "\\SomeFolder"));
That would extract the file test.rar to the folder SomeFolder. You can change the .rar extention to .iso, it'll work the same.
As far as I can see in your current code, there is no command given to extract a file, and no path to the file that has to be extracted. Try this example and let me know if it works =]
P.S. If you'd like to hide the extracting screen, you can set the YourProcessInfo.WindowStyle to ProcessWindowStyle.Hidden.
I hace confrunted recently with this kind of .iso extraction issue. After trying several methods, 7zip did the job for me, you just have to make sure that the latest version of 7zip is installed on your system. Maybe it will help
try
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
cmd.Start();
cmd.StandardInput.WriteLine("C:");
//Console.WriteLine(cmd.StandardOutput.Read());
cmd.StandardInput.Flush();
cmd.StandardInput.WriteLine("cd C:\\\"Program Files\"\\7-Zip\\");
//Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.StandardInput.Flush();
cmd.StandardInput.WriteLine(string.Format("7z x -y -o{0} {1}", source, copyISOLocation.TempIsoPath));
//Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
}
catch (Exception e)
{
Console.WriteLine(e.Message + "\n" + e.StackTrace);
if (e.InnerException != null)
{
Console.WriteLine(e.InnerException.Message + "\n" + e.InnerException.StackTrace);
}
}

How to Print any document in a SELECTED printer

I would like to print any document such as pdf,word,excel or text files in a selected printer using .net .I have got success to do such printing in the default printer .The only issue now is to print in the selected printer.
Here is the code for the printing.
public bool Print(string FilePath)
{
if (File.Exists(FilePath)) {
if (ShellExecute((System.IntPtr )1, "Print", FilePath, "", Directory.GetDirectoryRoot(FilePath), SW_SHOWNORMAL).ToInt32() <= 32) {
return false;
} else {
return true;
}
} else {
return false;
}
}
Process printJob = new Process();
printJob.StartInfo.FileName = path;
printJob.StartInfo.UseShellExecute = true;
printJob.StartInfo.Verb = "printto";
printJob.StartInfo.CreateNoWindow = true;
printJob.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
printJob.StartInfo.Arguments = "\"" + printerAddress + "\"" + " " + printerExtraParameters;
printJob.StartInfo.WorkingDirectory = Path.GetDirectoryName(path);
printJob.Start();
What file format are you testing with success to the default printer?
Its not possible to just send "any" document to a printer, generally the specific file format needs to be interpretted by an application that can read the file format then render it to a printer or a file that can be interpretted by the printer.
In most cases if you can render to a PostScript or PDF you can get its to print using a single interpretter.

Categories