How to run the installer from an iso file using c# code - c#

I have created an iso image with the installation folder of an application. I want to intialize the execution of the application form a .net code. I have been using the following code to open the image as a drive given that file explorer is the default application for opening iso files, then read the drives to check if there exists the file i want to run.
System.Diagnostics.Process.Start("C:\Users\tjdtud\Desktop\done\publish.iso");
private void button1_Click(object sender, EventArgs e)
{
DriveInfo[] diLocalDrives = DriveInfo.GetDrives();
try
{
foreach (DriveInfo diLogicalDrive in diLocalDrives)
{
if (File.Exists(diLogicalDrive.Name + "setup.exe"))
{
MessageBox.Show(diLogicalDrive.Name + "setup.exe");
System.Diagnostics.Process.Start(diLogicalDrive.Name + "\\setup.exe");
//MessageBox.Show("Logical Drive: " + diLogicalDrive.Name,
// "Logical Drives",
// MessageBoxButtons.OK,
// MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This code failes to work if file explorer is not the default iso opening application. Besides i have a strong feeling that it is not even close to the right way of doing it. Will very much appreciate any form of help or pointers to help links. Thank you for reading

You can use .NET DiscUtils to extract the file as follows:
using (FileStream isoStream = File.Open(#"C:\temp\sample.iso"))
{
CDReader cd = new CDReader(isoStream, true);
Stream fileStream = cd.OpenFile(#"Folder\Hello.txt", FileMode.Open);
// Use fileStream...
}
Extract the file to a temporary location and then execute it.

Related

Securing Temporary Files in C#

When working with an application on C# I am creating a few temporary files using the following logic:
Creating Temp File
private static string CreateTmpFile()
{
string fileName = string.Empty;
try
{
// Get the full name of the newly created Temporary file.
// Note that the GetTempFileName() method actually creates
// a 0-byte file and returns the name of the created file.
fileName = Path.GetTempFileName();
// Craete a FileInfo object to set the file's attributes
FileInfo fileInfo = new FileInfo(fileName);
// Set the Attribute property of this file to Temporary.
// Although this is not completely necessary, the .NET Framework is able
// to optimize the use of Temporary files by keeping them cached in memory.
fileInfo.Attributes = FileAttributes.Temporary;
Console.WriteLine("TEMP file created at: " + fileName);
}
catch (Exception ex)
{
Console.WriteLine("Unable to create TEMP file or set its attributes: " + ex.Message);
}
return fileName;
}
Writing to Temp File
private static void UpdateTmpFile(string tmpFile)
{
try
{
// Write to the temp file.
StreamWriter streamWriter = File.AppendText(tmpFile);
streamWriter.WriteLine("Hello from www.daveoncsharp.com!");
streamWriter.Flush();
streamWriter.Close();
Console.WriteLine("TEMP file updated.");
}
catch (Exception ex)
{
Console.WriteLine("Error writing to TEMP file: " + ex.Message);
}
}
I have also tried and followed some of the implementations found on this link for another question
and am using the following implementations in my code : Storing the file in the AppData Folder for using the ACL
However I have been asked to make sure that :
The temp files cannot be read by anyone(Not even the user) during application runtime,
And to make sure that they are deleted even when force closing the
application
For case 1: The temp files cannot be read by anyone(Not even the user) during application runtime,
How can I implement this for my application files? The temp files contain sensitive data which should not be readable even if the user themselves would like to read. Is there a way I can do that?
For case 2: To make sure that they are deleted even when force closing the
application
Here I would like to make sure than even with force close or a sudden restart the files are deleted.
If Force close: then delete the files before force close
If Restart: then delete the files on next startup
Are these doable?

How to create a basic package to store images?

How can I create a basic package to store images, like a zip file?
All I want to do is to store 20000 images inside one package. It will be easier for my hard disk.
Also, I need to be able to enter and exit from that package, read/write , add/remove files, using C# code.
Another file format is .iso that is close to what I want, but is complicated to operate with.
I want something very basic, not complicated. Basic as a library if possible.
Is there such a thing?
If you decide to go with the virtual hard disk the steps are the following:
In Computer management right click Disk management and in the local menu click 'Create VHD'. Create a virtual hard disk with the parameters you prefer. I recommend the .vhdx and dynamically expanding flavor. After this you have a mounted, un-initialized, un formatted hard drive.
Prepare it with the necessary and usual steps. As the result you will have a hard drive with an assigned drive letter.
Use it as any hard drive you have.
After reboot it will not be automatically mounted, you have to do it manually in Disk Management or use a scheduled task to mount the drive. Here's the script for that: https://gallery.technet.microsoft.com/scriptcenter/How-to-automatically-mount-d623ce34
You can unmount it at Disk Management as well.
You can copy the file yourdiskname.vhd(x) to other computers and use it.
Thank you all for your input
It helped me decide and it direction me to this answer I find after many web search battles.
I find a practical solution, but not that efficient as I want it.
Is moving slow-ish when cycling the images from inside a zip file, because it is unpacking each of them. I must re-think the code and unzip all into a stream or some lists. I will see. For now, is working and I am very happy :)
Here is the result I came up with:
//My code so far - not very efficient but is working.
using Ionic.Zip;
using Ionic.Zlib;
string zipPath = "0Images.zip";
void CountZipFiles()
{
using (ZipFile zip = new ZipFile(zipPath))
{
totalzipFiles = zip.Count-1;
}
}
Image emptyImage = Image.FromFile("emptyFemale.jpg");
void ReadZipImage()
{
using (ZipFile zip = new ZipFile(zipPath))
{
MemoryStream tempS = new MemoryStream();
for (int i = 0; i < zip.Count; i++)
{
if (i == countMyZipImages)
{
label1.Text = zip[i].FileName;
if (zip[i].FileName.Contains(".niet"))
{
pictureBox1.Image = emptyImage;
}
else
{
zip[i].Extract(tempS);
pictureBox1.Image = Image.FromStream(tempS);
}
}
}
}
}
int totalzipFiles = 0, countMyZipImages = 0;
private void button2_Click(object sender, EventArgs e)
{
countMyZipImages--;
if (countMyZipImages < 0) countMyZipImages = totalzipFiles;
textBox1.Text = countMyZipImages.ToString();
ReadZipImage();
}
private void button3_Click(object sender, EventArgs e)
{
countMyZipImages++;
if (countMyZipImages > totalzipFiles) countMyZipImages = 0;
textBox1.Text = countMyZipImages.ToString();
ReadZipImage();
}
// and this is a HELP file for later use - hopefully will help others too. ;)
How to add Ionic.Zip.dll in c#.net project and use it:
To add a reference, right click (in Solution Explorer on your project) Reference folder and select Add Reference.
Then browse and add the file Ionic.Zip.dll
//Important to add this using's too after referencing.
using Ionic.Zip;
using Ionic.Zlib;
private void CreateZIP_Click(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory named "files" in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
Exception ex = new Exception();
label1.Text = ex.Message;
}
}
//You can extract to a stream, or a fizical file !
private void button5_Click(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile("0Images.zip"))
{
MemoryStream tempS = new MemoryStream(); //stream
//{
foreach (ZipEntry ze in zip) //foreach
{
// check if you want to extract the image.name
if (ze.FileName == "00002 Riley Reid.jpg")
{
ze.Extract(tempS);
pictureBox1.Image = Image.FromStream(tempS);
}
}
//OR
for (int i = 0; i < zip.Count; i++) //for
{
if (i == countMyZipImages)
{
zip[i].Extract(tempS);
pictureBox1.Image = Image.FromStream(tempS);
}
}
//}
}
}
This is a free library I find on internet! I like it because is very little - 435kb. Here is a link I find for others if they want to use it. Dropbox - Ionic.Zip.dll[^]

The process cannot access the file 'C:\PCLtoMove\print.pcl' because it is being used by another process. Windows service

I have a folder named PCLtoMove. I have applied a filewatcherSystem in this folder to move files from this folder to another folder. first time when I start windows service It works fine but from next time it gives exception-
The process cannot access the file 'C:\PCLtoMove\fileName.pcl' because it is being used by another process.
my code to move file is -
private void SavionFileWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
{
try
{
string sourcePath = e.FullPath;
string destination = ConfigurationManager.AppSettings["destination"] + e.Name;
File.Move(sourcePath, destination);
}
catch (Exception ex)
{
this.EventLog.WriteEntry(ex.Message, EventLogEntryType.Information);
}
}
please tell me whats wrong I am doing.
I got the solution by adding following code to the above code. Its confirms that the file is completely moved or created.
FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.ReadWrite);
fs.ReadByte();
fs.Seek(0, SeekOrigin.Begin);
fs.Dispose();
File.Move(sourcePath,destination);
break;

Accessing txt file which is in solution

I'm trying to read some text from file
public void loadFromFile(string adress)
{
//int preventReadingEntireFile = 0;
try
{
using (StreamReader sr = new StreamReader(adress))
{
//preventReadingEntireFile++;
String line = sr.ReadToEnd();
Console.WriteLine(preventReadingEntireFile + ": " + line);
/*
* TODO: dodawanie słów do bazy
*/
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
But I don't know how to access this file (what the path is). I placed it in one of folers in my solution in my project. When I use "/TxtFiles/odm.txt" it searches for this file in "C:\TxtFiles\odm.txt" (which is wrong, there aren't any files like that there).
Is it possible? Do I have to make this file somehow "visible" for my scripts?
This is ASP.net mvc 5 project.
You have to use Server.MapPath() for it, which will generate absolute path of the file from relative url, the below code will work if TxtFiles directory is in root directory of Application:
StreamReader Sr = new StreamReader(Server.MapPath("~/TxtFiles/odm.txt"));
for you case:
string adress = "~/TxtFiles/odm.txt";
StreamReader Sr = new StreamReader(Server.MapPath(adress));
Looks like you're on Windows? A lot of programming languages (or rather, their file-handling libraries) interpret a starting slash '/' Unix-style, as "begin at the root of the file system", in your case, C:. Try doing "./TxtFiles/odm.txt", with an initial dot - this is conventionally interpreted as "start at the current directory".
Another option is to just use the full path, "C:\MyProjects\CurrentProject\TxtFiles\odm.txt".

Using Modi OCR To extract text from image

I Planned to use OCR in my project and searched more OCR methods and i didnt find anything correctly. And at last i heard about MODI and i tried that . But It throwing Following error:
Retrieving the COM class factory for component with CLSID {40942A6C-1520-4132-BDF8-BDC1F71F547B} failed due to the following error: 80040154
I'm Using Microsoft Office 2013 and visual studio 2012.
The code me using is follows:
private void button1_Click(object sender, EventArgs e)
{
CheckFileType(#"E:\\");
}
public void CheckFileType(string directoryPath)
{
IEnumerator files = Directory.GetFiles(directoryPath).GetEnumerator();
while (files.MoveNext())
{
//get file extension
string fileExtension = Path.GetExtension(Convert.ToString(files.Current));
//get file name without extenstion
string fileName=Convert.ToString(files.Current).Replace(fileExtension,string.Empty);
//Check for JPG File Format
if (fileExtension == ".jpg" || fileExtension == ".JPG") // or // ImageFormat.Jpeg.ToString()
{
try
{
//OCR Operations ...
MODI.Document md = new MODI.Document();
md.Create(Convert.ToString(files.Current));
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true);
MODI.Image image = (MODI.Image)md.Images[0];
//create text file with the same Image file name
FileStream createFile = new FileStream(fileName + ".txt",FileMode.CreateNew);
//save the image text in the text file
StreamWriter writeFile = new StreamWriter(createFile);
writeFile.Write(image.Layout.Text);
writeFile.Close();
}
catch (Exception)
{
MessageBox.Show("This Image hasn't a text or has a problem",
"OCR Notifications",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Can anyone help me in this ? Is that problem based on Microsoft Office version or Do i Need to make any changes ? Is that any better OCR dll ? thanks ..
The reason for the error is that Microsoft Office Document Imaging(MODI) has been discontinued with MS Office 2010. This is collaborated to OneNote in Office 2013.
Even I am still searching for the solutions or if there are any other tools to extract text from images programaticaly. If you know of any or have the solution, please share it.

Categories