Opening a file after writing to it - c#

I have a small app that writes to an excel file.
I would like for the program to immediately open the file after it has finished saving it.
How to go about doing just that?
Using Epplus to handle the excel.

if u just want to open file in C# u can just import
using System.Diagnostics;
then u can run process for "xlsx" file with Process.Start(string path);
class Program
{
static void Main()
{
Process.Start(#"C:\your.xlsx");
}
}

Process process = new Process();
process.StartInfo.FileName = "excel.exe";
process.StartInfo.Arguments = "myfyle.xls";
process.Start();

Related

C# open a pdf file using default application and delete the file after application is closed

I am converting a .txt file to a pdf and need to display the pdf to the user. For that, I have created a temporary .pdf file and created a process to open the file. This works fine when there is adobe acrobat installed. This fails when there is no default application. For my case, the pdf is opened in internet explorer and I get No process is associated with this object exception. Is there any other way to find out when the file is being closed so that I can delete it later on.
My code is like this.
HtmlToPdf htmlToPdf = new HtmlToPdf(pdfPrintOptions);
string tmpFileName = "zx" + DateTime.Now.Ticks + "x.pdf";
//Iron pdf does not handle in-memory pdf viewing
//convert it to pdf
htmlToPdf.RenderHTMLFileAsPdf(fileWithPath).SaveAs(tmpFileName);
// TempFileCollection tmpFileCollection = new TempFileCollection();
//Use windows process to open the file
Process pdfViewerProcess = new Process
{
EnableRaisingEvents = true, StartInfo = {FileName = tmpFileName}
};
pdfViewerProcess.Start();
pdfViewerProcess.WaitForExit(); **Failing in this line**
//Delete temporary file after the viewing windows is closed
if (File.Exists(tmpFileName))
{
File.Delete(tmpFileName);
}
Similar questions do not seem to provide a workaround for this problem. Any help will be appreciated. Thanks.
You have to define tmpFileName in global variable and use Event Exited like this:
try{
Process myProcess = new Process();
myProcess.StartInfo.FileName = tmpFileName;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.Start();
}
catch (Exception ex){
//Handle ERROR
return;
}
// Method Handle Exited event.
private void myProcess_Exited(object sender, System.EventArgs e){
if (File.Exists(tmpFileName))
{
File.Delete(tmpFileName);
}
}
Hope it can help you
Update my answers:
If it still not working. Try this answers
I would just save the PDF file in the TEMP folder.
Either in Windows User TEMP folder or your App can create a TEMP folder. If you create a TEMP folder just delete every file when your app closed.
string filePath = Path.GetTempPath() + "yourfile.pdf";
//Writer your file to Path
//File.WriteAllBytes(filePath, content);
Process.Start(filePath);

Code or command to use embedded resource in Visual Studio

Can somebody provide me a starting point or code to access an embedded resource using C#?
I have successfully embedded a couple of batch files, scripts and CAD drawings which I would like to run the batch and copy the scripts and CAD files to a location specified in the batch file.
I'm struggling to find how to specify what the item is and set the path within the EXE. The below code is what I thought would work, but it failed and the others I found online all related to XML files.
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + "\\Batchfile.bat";
p.Start();
I honestly don't even know if I'm looking at the correct way to do this as this is my first time using either C# or Visual Studio.
Open Solution Explorer add files you want to embed. Right click on the files then click on Properties. In Properties window and change Build Action to Embedded Resource.
After that you should write the embedded resources to file in order to be able to run it.
using System;
using System.Reflection;
using System.IO;
using System.Diagnostics;
namespace YourProject
{
public class MyClass
{
// Other Code...
private void StartProcessWithFile()
{
var assembly = Assembly.GetExecutingAssembly();
//Getting names of all embedded resources
var allResourceNames = assembly.GetManifestResourceNames();
//Selecting first one.
var resourceName = allResourceNames[0];
var pathToFile = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory) +
resourceName;
using (var stream = assembly.GetManifestResourceStream(resourceName))
using (var fileStream = File.Create(pathToFile))
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(fileStream);
}
var process = new Process();
process.StartInfo.FileName = pathToFile;
process.Start();
}
}
}

Batch file stuck while unziping large files, when called from windows service..!

I have a windows service that calls a batch file. Batch file then calls commands to zip and unzip text files. Sometimes, while unzipping large files (approx. = 900MB) the process get stuck in between and then I have to stop windows service to release the process.Can anyone please suggest some solution to this problem?
I use following code to call batch file and retrieve return code from it:
objProcessStartInfo = new ProcessStartInfo(#out_Batch_File_Name);
objProcessStartInfo.UseShellExecute = false;
objProcessStartInfo.RedirectStandardOutput = true;
objProcessStartInfo.RedirectStandardError = true;
objProcessStartInfo.CreateNoWindow = true;
process = new Process();
process.Start Info = objProcessStartInfo;
process.Start();
process.WaitForExit();
returnCode = process.ExitCode;

Executing BatchFile from C# program

I am writing the batch file and executing it through C# program.
Writing Batch file :
I will get the Path, Executable name and arguments from app.config and write them to a batch file.
Executing Batch file :
Once I write the batch file I pass the file name to below function which executes the batch file to launches an application.
Problem :
My program will write a lot of batch files which are executed immediately after each and every file is written. I find that, some times the applications are not started which means that batch files are not executed. I didn't even get any error messages or prompts for this failure of batch file execution.
Expected solution :
Any problem in executing the batch file, I should be able to log it or prompt an error.
Code that executes Batch File :
System.Diagnostics.ProcessStartInfo procinfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
procinfo.UseShellExecute = false;
procinfo.RedirectStandardError = true;
procinfo.RedirectStandardInput = true;
procinfo.RedirectStandardOutput = true;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(procinfo);
System.IO.StreamReader stream = System.IO.File.OpenText(BatchPath + LatestFileName);
System.IO.StreamReader sroutput = process.StandardOutput;
System.IO.StreamWriter srinput = process.StandardInput;
while (stream.Peek() != -1)
{
srinput.WriteLine(stream.ReadLine());
}
Log.Flow_writeToLogFile("Executed .Bat file : " + LatestFileName);
stream.Close();
process.Close();
srinput.Close();
sroutput.Close();
I'm not sure where your problem lies specifically but I've had no problems with the following code:
using (FileStream file = new FileStream("xyz.cmd", FileMode.Create)) {
using (StreamWriter sw = new StreamWriter(file)) {
sw.Write("#echo ====================\n");
sw.Close();
}
}
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "xyz.cmd";
//p.StartInfo.RedirectStandardOutput = true;
p.Start();
//String s = p.StandardOutput.ReadLine();
//while (s != null) {
// MessageBox.Show(s);
// s = p.StandardOutput.ReadLine();
//}
p.WaitForExit();
Obviously that's been cut down a bit for the purposes of hiding my "secret sauce" but that's code currently being used in production without issues.
I do have one question. Why don't you execute the cmd file directly rather than running cmd.exe?
Probably the first thing I'd do is to print out the BatchPath + LatestFileName value to see if you're creating any weirdly named files which would prevent cmd.exe from running them.

Auto FTP from a Directory

I want to monitor a directory and FTP any files that are place there to an FTP location. does anyone know how to do this in c#?
Thanks
EDIT: Anyone know of a good client that can monitor a directory and FTP and files placed in it?
I combination of the System.IO.FileSystemWatcher and System.Net.FtpWebRequest/FtpWebResponse classes.
We need more information to be more specific.
When used in conjunction with the FileSystemWatcher, this code is a quick and dirty way to upload a file to a server.
public static void Upload(string ftpServer, string directory, string file)
{
//ftp command will be sketchy without this
Environment.CurrentDirectory = directory;
//create a batch file for the ftp command
string commands = "\n\nput " + file + "\nquit\n";
StreamWriter sw = new StreamWriter("f.cmd");
sw.WriteLine(commands);
sw.Close();
//start the ftp command with the generated script file
ProcessStartInfo psi = new ProcessStartInfo("ftp");
psi.Arguments = "-s:f.cmd " + ftpServer;
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit();
File.Delete(file);
File.Delete("f.cmd");
}

Categories

Resources