Process.Start from .txt file to textbox - c#

I'm trying to solve a problem i got. My job is to make little app, that will show text which is inside of .txt file in the app window, but for some reason they told me that i have to use # ShellExecute(use Process.Start).
Is there even a way to do it? Because when i use ShellExecute, that file opens in notepad after button press, which is, I guess, point of using Shell.
There is little code of what i tried to do, but without success.
Thanks in advice!
string filePath = #"C:\Folder\file.txt";
ProcessStartInfo psi = new ProcessStartInfo(filePath);
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.CreateNoWindow = true;
var proc = Process.Start(psi);
string s = proc.StandardOutput.ReadToEnd();
textBox1.Text = s;

Instead of using ProcessStartInfo, try StreamReader like this :
string filePath = #"C:\Folder\file.txt";
StreamReader sr = new StreamReader(filePath);
string s = sr.ReadToEndAsync().GetAwaiter().GetResult();
Console.WriteLine(s);
Use Async method to read all text without blocking.

If you absolutely need to do that, you can create a second application TxtToTextBox, which you can run from your first application using Process.Start (initialize ProcessStartInfo with the path to that application instead of the txt file).
Then you can give that process an argument pointing to the file using psi.Arguments = $"\"{filePath}\"; (this also adds quotation marks around your path, so spaces are escaped).
Then in your second application you can do the sane thing, and simply read the file with File.ReadAllLines(args[0]) and print that into your text box.
If possible, I would recommend talking to whoever told you to use Process.Start and asking them for more reasons as to why you should use is, as this is one of the most roundabout ways to do this I could think of.

Related

FFMPEG C# Winforms Output to Textbox

Trying to write a video compression app using Windows Forms, I can get the file to compress ok, but I'm looking to show the process to something like a textbox?
At the minute the program doesn't have a progress, so you don't know if its complete or not, is it possible to output with FFMPEG is doing to a textbox?
This is my code, when it runs nothing is shown in the textbox:
string ffmpeg = #"c:\test\ffmpeg.exe";
ProcessStartInfo psi = new ProcessStartInfo(ffmpeg);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.Arguments = "-i c:\\test\\small.mp4 -s 480x272 c:\\test\\compressed.mp4";
var proc = Process.Start(psi);
string s = proc.StandardOutput.ReadToEnd();
textBox1.Text = s;
Do i need to pass something else into the ProcessStartInfo section?
You need to periodically check back with proc.StandardOutput to see if there is new text there. Right immediately after you've started the program, it's no surprise that it hasn't managed to write anything yet.
I'd advise using a Timer for that.

forcing to close a file

I have file that another process using it.
and I want to force closing the file. so that I will work on the fill.
I tried to use Handle.exe however it didn't find the process
would appreiciate some help here is my code:
Process tool = new Process();
tool.StartInfo.FileName = handlPath;
tool.StartInfo.Arguments = _pathDirectory + " /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = #"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
}
I'm sure, that if a program really holds an exclusive access to a file, it has a reason to do it. For example, Windows Explorer holds it when the file is in copying process.
Very often, programs open a file for a writing, but do not actively write to it. For example, when you open a document in MS Word, it is copied to the temp file and a source file is just "open for writing". You'll still have an exception if you use standard File.Open method, but you can copy it to a temp file using File.Copy.
Alternatively, you can explicitly specify FileShare.ReadWrite parameter and get an access to a file. In this case, other program will have problems with accessing a file.
If you have mentioned the file name or type it would have been more easier, anyway try using the cmd for this. Get the process name and replace ProcessName.exe of the following code.
First you'll have to add using System.Diagnostics; on top.
Process.Start("cmd.exe", "/c taskkill /F /IM ProcessName.exe");

Print multiple images using Process.StartInfo.Verb=“print” command

I am using this code for print with windows print pictures...
string fileName = #"C:\Images\12.jpg";
var p = new Process();
p.StartInfo.FileName = fileName;
p.StartInfo.Verb = "Print";
p.Start();
I want to open multiple images from directory into this, how can i do it?
I tried this code, but does not work:
var p = new Process();
DirectoryInfo d = new DirectoryInfo(#"Directory address");
FileInfo[] Files = d.GetFiles("*.jpg");
foreach (FileInfo file in Files)
{
p.StartInfo.FileName += file.FullName.ToList();
p.StartInfo.Verb = "Print";
p.Start();
}
From your code example, it appears you want to simply invoke separate "print" verb commands for each file. If so, then you should be able to accomplish that by simply assigning the file name in your loop, instead of enumerating the characters of the file name and appending that to the FileName property:
DirectoryInfo d = new DirectoryInfo(#"Directory address");
FileInfo[] Files = d.GetFiles("*.jpg");
ProcessStartInfo psi = new ProcessStartInfo();
psi.Verb = "Print";
foreach (FileInfo file in Files)
{
psi.FileName = file.FullName;
Process.Start(psi);
}
Note that you can't reuse a single Process object for this purpose. Once a given Process object has been started, it can't be started again. But you can reuse a ProcessStartInfo object, starting a new process with each iteration of the loop.
EDIT:
From your comment:
I do not want to simply invoke separate "print" verb commands for each file...I want to add all files in one "print" verb command
This is not possible using the Process class. By definition, the DDE "print" verb (i.e. "command") handles only a single document. If you are willing to do a lot of extra work, you can write your own DDE client that attempts to use DDEEXEC to iteratively interact with a DDE server that knows how to print your image files. But a) this is a lot more work, and b) it still will only work if you happen to have a program installed that handles printing of image files via DDEEXEC (the Windows built-in support for printing images does not).
I recommend you stick with the above.
(And for future reference, if you only want to call Process.Start() once, putting it inside a loop is definitely not the way to go. Your question would have been more clear if your example code bore any resemblance at all to what you were actually trying to do. :) )

How to write a "*.bat" file?

Why "1.bat" can't run successfully? Any help will be appreciate. "1.bat" was created successfully.It can run without error, but can't rename the files.
private void button1_Click(object sender, EventArgs e)
{
string str = System.Environment.CurrentDirectory;
str += "\\1.bat";
string txt = "";
txt = "ren *.mp3 *.wav";
StreamWriter sw = new StreamWriter(str,false, Encoding.UTF8);
sw.Write(txt);
sw.Close();
Process p = new Process();
p.StartInfo.FileName = str;
p.StartInfo.Arguments = "";
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.Start();
}
One problem is that your file is being written with a UTF-8 BOM. Try passing Encoding.Default to test this out. Or pass new UTF8Encoding(false) as the encoding to pass a UTF-8 encoding that omits the BOM.
Another problem (which you just added in an edit) is that you set UseShellExecute to false. That requires the file you pass to be an executable file. Your file isn't. You need UseShellExecute to be true to allow the shell to work out how to process your .bat file.
And yet another possible problem is that the current directory may not be what you think it is.
When faced with problems like this there is no need at all to be helpless. Do some debugging. Add a pause at the end of your batch file and make sure that you can see the console. You'll find out immediately what the problem is. Learning how to debug is just as important as learning how to program. You won't be able to do the latter until you can do the former.
If I were having to do it this way, with an external process, I would:
Set UseShellExecute to false.
Pass cmd.exe as the executable file.
Pass the command to be executed as the command line.
However, it would be much easier to do this directly using C# and so avoid having to spin up external processes.

How can I get filename when user close Word?

I have one button and one textbox on form. When I click on the button, Microsoft Word is started. When the user closes Word, I want to get the file name that the user saved his work under to show up in the text box.
I am using the following code for button_click:
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(#"C:\Program Files\Microsoft Office\Office12\winword.exe");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader myOutput = listFiles.StandardOutput;
listFiles.WaitForExit();
if (listFiles.HasExited)
{
System.IO.FileInfo ff = new System.IO.FileInfo(myOutput.ToString());
string output = myOutput.ReadToEnd();
this.processResults.Text = output;
}
I don't believe this is possible via the command line. Also, realize that, if the user opens another document, your code will not finish, since it'll wait until all of the docs are closed (the process won't end until that point).
That being said, you should be able to use the Word/Office Interop libraries, and listen to the DocumentBeforeSave and/or DocumentBeforeClose events. This should let you pull the information from the Document itself, right as it's being saved/closed.
I don't think you can do this with the current code you have. ProcessStartInfo is very generic and has no knowledge of word.
I think you will want to use Visual Studio Tools for Office (VSTO) to start word. This way you have a reference to the word application and document and can get the document name.
this article should get you started http://www.c-sharpcorner.com/UploadFile/mgold/WordFromDotNet11082005235506PM/WordFromDotNet.aspx the sample code has a object called aDoc. Then after the save you can check aDoc.FullName to get the path.
I'm not sure whether it's possible or not because name of the saved file is an internal information that's not public for other applications.
Instead in your particular case since you are using MS Word you can use Word interop to start the Word application in your application and then handle its events
Create a blank Word document in the desired location, and then get Word to load that?

Categories