I have to run an exe file through C# code and open the output file generated by the exe to do some pre-processing.
The output file is generated successfully by running the exe. But when I try to open the output file at the same run, I am getting File Not Found Exception but when I run the program again, the code reads my output file and I am able to do the pre-processing.
private static void launchExe()
{
string filename = Path.Combine("//myPathToExe");
string cParams = "argumentsToExe";
var proc = System.Diagnostics.Process.Start(filename, cParams);
proc.Close();
}
I now need to open the output file generated by the exe.
private static void openOutputFile()
{
StreamReader streamReader = new StreamReader("//PathToOutputFile");
string content = streamReader.ReadToEnd();
/*
* Pre Processing Code
*/
}
At this stage I am getting File Not Found Exception but I have the output file generated in the specified path.
Kindly help me with this issue.
Don't close your app, but WaitForExit.
string filename = Path.Combine("//myPathToExe");
string cParams = "argumentsToExe";
var proc = System.Diagnostics.Process.Start(filename, cParams);
proc.WaitForExit();
Related
i try to write line in file when this exists:
My code is next:
string strRuta = "C:\File.txt"
if (!Directory.Exists(strRuta))
Directory.CreateDirectory(strRuta);
string psContenido = "Hola";
if (!(File.Exists(strRuta + strNombreArchivo)))
{
swArchivo = File.CreateText(strRuta + strNombreArchivo);
}
if (!psContenido.ToLower().Contains("error"))
{
swArchivo.WriteLine(psContenido);
swArchivo.Flush();
swArchivo.Close();
swArchivo.Dispose();
File.SetCreationTime(strRuta + strNombreArchivo, DateTime.Now);
}
but when run this program i have a error in WriteLine, i donĀ“t undertand which is the reason, could you help me?
I would like to know how to write in the file(in the next line the word)
There are a couple of problems, I think. First, you're specifying what looks like a file name and creating a directory with that name (not sure if this is intentional or not). Second, you can use the static helper method AppendAllText of the File class to both create the file if it doesn't exist, and to write the contents to the end of the file. It handles all the streamwriter stuff for you, so you don't have to worry about calling close and dispose.
private static void Main(string[] args)
{
string directory = #"C:\private\temp";
string fileName = "MyFile.txt";
string filePath = Path.Combine(directory, fileName);
string fileContents = "This will be written to the end of the file\r\n";
// This will create the directory if it doesn't exist
Directory.CreateDirectory(directory);
// This will create the file if it doesn't exist, and then write the text at the end.
File.AppendAllText(filePath, fileContents);
File.SetCreationTime(filePath, DateTime.Now);
}
I've downloaded an executable file from my Cloud blob, and now I want to run the file.
here's my relevant piece of code:
Stream codeContent = new MemoryStream();
blobClientCode.GetBlockBlobReference(codeUri).DownloadToStream(codeContent);
codeContent.Position = 0;
Process p = new Process();
Now I want to run the executable I've downloaded. I guess that I need to use a Process for that, I just don't know how. can anyone please help?
Thanks in advance
Something like this should do. Pass your blob as the first parameter and the local file path as the second:
public static void RunBlob(ICloudBlob blob, string targetFilePath) {
using (var fileStream = File.OpenWrite(targetFilePath)) {
blob.DownloadToStream(fileStream);
}
var process = new Process() {StartInfo = new ProcessStartInfo(targetFilePath)};
process.Start();
process.WaitForExit(); // Optional
}
I was trying to print a pdf document in the background using a console application. I used the process for doing it. The console application sends the pdf file to the printer, But the adobe reader that is opened in the background in minimized mode is throwing the following error "There was an error opening this document. This file cannot be found". As a result of this while printing multiple times, I was not able to kill the process. Is there any possibility of getting rid of this error?
My requirement is to print the pdf file using process and while doing that the pdf file must be opened in the minimized mode and once done printing the reader needs to be closed automatically. I have tried the following code, but still throws the error..
string file = "D:\\hat.pdf";
PrinterSettings ps = new PrinterSettings();
string printer = ps.PrinterName;
Process.Start(Registry.LocalMachine.OpenSubKe(#"SOFTWARE\Microsoft\Windows\CurrentVersion"+#"\App Paths\AcroRd32.exe").GetValue("").ToString(),string.Format("/h /t \"{0}\" \"{1}\"", file, printer));
since you want to have Acrobat reader open in the background when you want to print the document, you could use something like:
private static void RunExecutable(string executable, string arguments)
{
ProcessStartInfo starter = new ProcessStartInfo(executable, arguments);
starter.CreateNoWindow = true;
starter.RedirectStandardOutput = true;
starter.UseShellExecute = false;
Process process = new Process();
process.StartInfo = starter;
process.Start();
StringBuilder buffer = new StringBuilder();
using (StreamReader reader = process.StandardOutput)
{
string line = reader.ReadLine();
while (line != null)
{
buffer.Append(line);
buffer.Append(Environment.NewLine);
line = reader.ReadLine();
Thread.Sleep(100);
}
}
if (process.ExitCode != 0)
{
throw new Exception(string.Format(#"""{0}"" exited with ExitCode {1}. Output: {2}",
executable, process.ExitCode, buffer.ToString());
}
}
You can print your PDF by incorporating the above code into your project and using it as follows:
string pathToExecutable = "c:\...\acrord32.exe";
RunExecutable(pathToExecutable, #"/t ""mytest.pdf"" ""My Windows PrinterName""");
this code was taken from http://aspalliance.com/514_CodeSnip_Printing_PDF_from_NET.all
If you do not need to have Acrobat Reader open in the background, and just print the pdf like any other document, you can have a look at the PrintDocument class:
http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.print.aspx
I am unable to open the file just after creating the file in c# webservice code .
The directory is not present initially. So the program creates the directory and the file. Then tries to open the file to write a line. But it fails to open the file. The error is the file is open in another process.
I tried to open the file from windows explorer. the file opens but error message is still coming.
I tried to delete the folder C:\Test, it says file is open is in WebDev.WebDevServer40.exe
Any help please.
[WebMethod]
public string saveFileUploaderName(string name)
{
string path = "c:\\Test";
string filename = "Test.txt";
string completeFileName = Path.Combine(path,filename);
if(!File.Exists(completeFileName))
{
Directory.CreateDirectory(path);
File.Create(completeFileName);
}
StreamWriter writer = File.AppendText(completeFileName);
writer.WriteLine(name);
writer.Flush();
writer.Close();
return "success";
}
File.Create returns a stream, but you're discarding it.
So (I think!) you either need to use the returned stream, or explicitly close it before trying to open a new stream to the same file.
You need to close the file, try:
File.Create(completeFileName).Close();
Use the File.AppendAllText instead.
This will create the file if it doesn't exist.
Your code would be as simple as
[WebMethod]
public string saveFileUploaderName(string name)
{
string path = "c:\\Test";
string filename = "Test.txt";
string completeFileName = Path.Combine(path,filename);
File.AppendAllText(completeFileName, name);
return "success";
}
How would I open a file, perform some regex on the file, and then save the file?
I know I can open a file, read line by line, but how would I update the actual contents of a file and then save the file?
The following approach would work regardless of file size, and will also not corrupt the original file in anyway if the operation would fail before it is complete:
string inputFile = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "temp.txt");
string outputFile = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "temp2.txt");
using (StreamReader input = File.OpenText(inputFile))
using (Stream output = File.OpenWrite(outputFile))
using (StreamWriter writer = new StreamWriter(output))
{
while (!input.EndOfStream)
{
// read line
string line = input.ReadLine();
// process line in some way
// write the file to temp file
writer.WriteLine(line);
}
}
File.Delete(inputFile); // delete original file
File.Move(outputFile, inputFile); // rename temp file to original file name
string[] lines = File.ReadAllLines(path);
string[] transformedLines = lines.Select(s => Transform(s)).ToArray();
File.WriteAllLines(path, transformedLines);
Here, for example, Transform is
public static string Transform(string s) {
return s.Substring(0, 1) + Char.ToUpper(s[1]) + s.Substring(2);
}
Open the file for read. Read all the contents of the file into memory. Close the file. Open the file for write. Write all contents to the file. Close the file.
Alternatively, if the file is very large:
Open fileA for read. Open a new file (fileB) for write. Process each line of fileA and save to fileB. Close fileA. Close fileB. Delete fileA. Rename fileB to fileA.
Close the file after you finish reading it
Reopen the file for write
Write back the new contents