I am currently trying to open a PDF file on page 16 using System.Diagnostics.Process.Start, but it won't pick up my file path. Here is my file path that I wish to open from C:\Users\ipadc\Desktop\projek\Bookstore Bargainer System (4 Sept)\BookstoreBargainerSystem\bin\Debug\Pdfs\User_Manual. Iit is stored in my Application.StartupPath.
Here is the code i have tried but it says that it cannot find the path.
System.Diagnostics.Process.Start(
"Acrobat.exe /A \"page=16\" \""+Application.StartupPath+ "\\Pdfs\\User_Manual.pdf");
but it simply says The file does not exist.
Anybody knows why it cannot find this file. The file is an Adobe Acrobat type saved as .pdf.
Your arguments cannot be part of the process.start. This takes in the executable name.
The file name and arguments are different and need to be separated.
Process acro = new Process();
acro.StartInfo.FileName = "Acrobat.exe"
acro.StartInfo.Arguments = "/A \"page=16\" \""+Application.StartupPath+ "\Pdfs\User_Manual.pdf\""
acro.Start();
I also added an extra quote at the end of your path.
You can also do this instead, notice the arguments are a 2nd parameter of start here:
Process.Start("Acrobat.exe", "/A \"page=16\" \""+Application.StartupPath+ "\Pdfs\User_Manual.pdf\"");
And path the Path.Combine recommendation added (Marco's comment is right).
Process.Start("Acrobat.exe",
"/A \"page=16\" \"" +
System.IO.Path.Combine(Application.StartupPath, "Pdfs", "User_Manual.pdf")
+ "\"");
Related
I am trying to open PDF files in Adobe reader using C#'s Process.Start().
When I provide a path without white spaces it works fine, but paths and pdf files containing white spaces don't open.
This is my code:
Button btn = (Button)sender;
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "AcroRd32";
string s = btn.Tag.ToString();
//btn.Tag Contains the full file path
info.Arguments = s;
Process.Start(info);
If it is C:\\Users\\Manish\\Documents\\ms_Essential_.NET_4.5.pdf it works fine but if it is F:\\Tutorials\\C#\\Foundational\\Microsoft Visual C# 2012 Step By Step V413HAV.pdf Adobe Reader gives an error saying there was an error in opening the document file can't be found.
I have read through many questions related to this topic in SO but it won't work. As I can't figure out how to apply # prefix in my string s.
Any ideas how to fix this?
Just a little trick there is a default PDF reader set on the client: just use the file name as FileName if the process. Usually you don't care which program to use, so then this solution just works:
Process.Start(pdfFileName);
This doesn't need special quoting too, so it instantly fixes your problem.
Try to wrap the arguments around quotes:
info.Arguments = "\"" + s + "\"";
Using the character # before the string value should work:
var path = #"F:\Tutorials\C#\Foundational\Microsoft Visual C# 2012 Step By Step V413HAV.pdf";
You should enquote the path provided in the argument list. This will cause it to view the path as a single argument instead of multiple space separated arguments:
info.Arguments = "\"" + s + "\"";
I already know how to browse for an image using open file dialog. So let's say we already got the path :
string imagePath = "Desktop/Images/SampleImage.jpg";
I want to copy that file, into my application folder :
string appFolderPath = "SampleApp/Images/";
How to copy the given image to the appFolderPath programmatically?
Thank you.
You could do something like this:
var path = Path.Combine(
System.AppDomain.CurrentDomain.BaseDirectory,
"Images",
fileName);
File.Copy(imagePath, path);
where fileName is the actual name of the file only (including the extension).
UPDATE: the Path.Combine method will cleanly combine strings into a well-formed path. For example, if one of the strings does have a backslash and the other doesn't it won't matter; they are combined appropriately.
The System.AppDomain.CurrentDomain.BaseDirectory, per MSDN, does the following:
Gets the base directory that the assembly resolver uses to probe for assemblies.
That's going to be the executable path you're running in; so the path in the end (and let's assume fileName is test.txt) would be:
{path_to_exe}\Images\test.txt
string path="Source imagepath";
File.Copy(System.AppDomain.CurrentDomain.BaseDirectory+"\\Images", path);
\ System.AppDomain.CurrentDomain.BaseDirectory is to provide path of the application folder
I am using the code below to pass an argument to a process
ProcessStartInfo StartInfo = new ProcessStartInfo();
StartInfo.FileName = HttpContext.Current.Server.MapPath(#"\highcharts\phantomjs.exe");
StartInfo.Arguments = HttpContext.Current.Server.MapPath(#"\highcharts\highcharts-convert.js");
StartInfo.Arguments += #" -outfile " + path + #"\chart" + templateData[i].ReportTemplateChartId + ".png -width 800 -infile " + chartoptions1;
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = false;
In chartoptions1 I was using a JSON string, but it throws an exception saying string filename too long, so I created a text file and tried to pass it, but the chart image is not generated.
From this MSDN page,
On Windows Vista and earlier versions of the Windows operating
system, the length of the arguments added to the length of the full
path to the process must be less than 2080. On Windows 7 and later
versions, the length must be less than 32699.
Did you check the length of StartInfo.Arguments ?
On the other part, a quick look at this wiki page on Github,
-infile: The file to convert, assumes it's either a JSON file, the script checks for the input file to have the extension '.json', or
otherwise it assumes it to be an svg file.
So, -infile should be a file and not a JSON content. I suppose your chartoptions1 is quite large, so you have the error message string filename too long.
Highcharts may also check the length of the infile path (256 ?)
The running script should have at least read access to the infile and should be resolvable ; especially if you don't specified a working directory, you have to add the full path with infile and not just the filename.
To debug, a working directory issue, simply test with a constant path such as c:\test
I am trying to write out a text file to: C:\Test folder\output\, but without putting C:\ in.
i.e.
This is what I have at the moment, which currently works, but has the C:\ in the beginning.
StreamWriter sw = new StreamWriter(#"C:\Test folder\output\test.txt");
I really want to write the file to the output folder, but with out having to have C:\ in the front.
I have tried the following, but my program just hangs (doesn't write the file out):
(#"\\Test folder\output\test.txt");
(#".\Test folder\output\test.txt");
("//Test folder//output//test.txt");
("./Test folder//output//test.txt");
Is there anyway I could do this?
Thanks.
Thanks for helping guys.
A colleague of mine chipped in and helped as well, but #Kami helped a lot too.
It is now working when I have:
string path = string.Concat(Environment.CurrentDirectory, #"\Output\test.txt");
As he said: "The CurrentDirectory is where the program is run from.
I understand that you would want to write data to a specified folder. The first method is to specify the folder in code or through configuration.
If you need to write to specific drive or current drive you can do the following
string driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
string path = diveLetter + #"Test folder\output\test.txt";
StreamWriter sw = new StreamWriter(path);
If the directory needs to be relative to the current application directory, then user AppDomain.CurrentDomain.BaseDirectory to get the current directory and use ../ combination to navigate to the required folder.
You can use System.IO.Path.GetDirectoryName to get the directory of your running application and then you can add to this the rest of the path..
I don't get clearly what you want from this question , hope this get it..
A common technique is to make the directory relative to your exe's runtime directory, e.g., a sub-directory, like this:
string exeRuntimeDirectory =
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
string subDirectory =
System.IO.Path.Combine(exeRuntimeDirectory, "Output");
if (!System.IO.Directory.Exists(subDirectory))
{
// Output directory does not exist, so create it.
System.IO.Directory.CreateDirectory(subDirectory);
}
This means wherever the exe is installed to, it will create an "Output" sub-directory, which it can then write files to.
It also has the advantage of keeping the exe and its output files together in one location, and not scattered all over the place.
I have a batch file with following content:
echo %~dp0
CD Arvind
echo %~dp0
Even after changing directory value of %~dp0 is the same.
However, if I run this batch file from CSharp program, the value of %~dp0 changes after CD. It now points to new directory. Following is the code that I use:
Directory.SetCurrentDirectory(//Dir where batch file resides);
ProcessStartInfo ProcessInfo;
Process process = new Process();
ProcessInfo = new ProcessStartInfo("mybatfile.bat");
ProcessInfo.UseShellExecute = false;
ProcessInfo.RedirectStandardOutput = true;
process = Process.Start(ProcessInfo);
process.WaitForExit();
ExitCode = process.ExitCode;
process.Close();
Why is there a difference in output on executing same script by different ways?
Do I miss something here?
This question started the discussion on this point, and some testing was done to determine why. So, after some debugging inside cmd.exe ... (this is for a 32 bit Windows XP cmd.exe but as the behaviour is consistent on newer system versions, probably the same or similar code is used)
Inside Jeb's answer is stated
It's a problem with the quotes and %~0.
cmd.exe handles %~0 in a special way
and here Jeb is correct.
Inside the current context of the running batch file there is a reference to the current batch file, a "variable" containing the full path and file name of the running batch file.
When a variable is accessed, its value is retrieved from a list of available variables but if the variable requested is %0, and some modifier has been requested (~ is used) then the data in the running batch reference "variable" is used.
But the usage of ~ has another effect in the variables. If the value is quoted, quotes are removed. And here there is a bug in the code. It is coded something like (here simplified assembler to pseudocode)
value = varList[varName]
if (value && value[0] == quote ){
value = unquote(value)
} else if (varName == '0') {
value = batchFullName
}
And yes, this means that when the batch file is quoted, the first part of the if is executed and the full reference to the batch file is not used, instead the value retrieved is the string used to reference the batch file when calling it.
What happens then? If when the batch file was called the full path was used, then there will be no problem. But if the full path is not used in the call, any element in the path not present in the batch call needs to be retrieved. This retrieval assumes relative paths.
A simple batch file (test.cmd)
#echo off
echo %~f0
When called using test (no extension, no quotes), we obtain c:\somewhere\test.cmd
When called using "test" (no extension, quotes), we obtain c:\somewhere\test
In the first case, without quotes, the correct internal value is used. In the second case, as the call is quoted, the string used to call the batch file ("test") is unquoted and used. As we are requesting a full path, it is considered a relative reference to something called test.
This is the why. How to solve?
From the C# code
Don't use quotes : cmd /c batchfile.cmd
If quotes are needed, use the full path in the call to the batch file. That way %0 contains all the needed information.
From the batch file
Batch file can be invoked in any way from any place. The only reliable way to retrieve the information of the current batch file is to use a subroutine. If any modifier (~) is used, the %0 will use the internal "variable" to obtain the data.
#echo off
setlocal enableextensions disabledelayedexpansion
call :getCurrentBatch batch
echo %batch%
exit /b
:getCurrentBatch variableName
set "%~1=%~f0"
goto :eof
This will echo to console the full path to the current batch file independtly of how you call the file, with or without quotes.
note: Why does it work? Why the %~f0 reference inside a subroutine return a different value? The data accessed from inside the subroutine is not the same. When the call is executed, a new batch file context is created in memory, and the internal "variable" is used to initialize this context.
I'll try to explain why this behaves so oddly. A rather technical and long-winded story, I'll try to keep it condense. Starting point for this problem is:
ProcessInfo.UseShellExecute = false;
You'll see that if you omit this statement or assign true that it works as you expected.
Windows provides two basic ways to start programs, ShellExecuteEx() and CreateProcess(). The UseShellExecute property selects between those two. The former is the "smart and friendly" version, it knows a lot about the way the shell works for example. Which is why you can, say, pass the path to an arbitrary file like "foo.doc". It knows how to look up the file association for .doc files and find the .exe file that knows how to open foo.doc.
CreateProcess() is the low-level winapi function, there's very little glue between it and the native kernel function (NtCreateProcess). Note the first two arguments of the function, lpApplicationName and lpCommandLine, you can easily match them to the two ProcessStartInfo properties.
What is not so visible that CreateProcess() provides two distinct ways to start a program. The first one is where you leave lpApplicationName set to an empty string and use lpCommandLine to provide the entire command line. That makes CreateProcess friendly, it automatically expands the application name to the full path after it has located the executable. So, for example, "cmd.exe" gets expanded to "c:\windows\system32\cmd.exe". But it does not do this when you use the lpApplicationName argument, it passes the string as-is.
This quirk has an effect on programs that depend on the exact way the command line is specified. Particularly so for C programs, they assume that argv[0] contains the path to their executable file. And it has an effect on %~dp0, it too uses that argument. And flounders in your case since the path it works with is just "mybatfile.bat" instead of, say, "c:\temp\mybatfile.bat". Which makes it return the current directory instead of "c:\temp".
So what your are supposed to do, and this is totally under-documented in the .NET Framework documentation, is that it is now up to you to pass the full path name to the file. So the proper code should look like:
string path = #"c:\temp"; // Dir where batch file resides
Directory.SetCurrentDirectory(path);
string batfile = System.IO.Path.Combine(path, "mybatfile.bat");
ProcessStartInfo = new ProcessStartInfo(batfile);
And you'll see that %~dp0 now expands as you expected. It is using path instead of the current directory.
Joey's suggestion helped.
Just by replacing
ProcessInfo = new ProcessStartInfo("mybatfile.bat");
with
ProcessInfo = new ProcessStartInfo("cmd", "/c " + "mybatfile.bat");
did the trick.
It's a problem with the quotes and %~0.
cmd.exe handles %~0 in a special way (other than %~1).
It checks if %0 is a relative filename, then it prepend it with the start directory.
If there a file can be found it will use this combination, else it prepends it with the actual directory.
But when the name begins with a quote it seems to fail to remove the quotes, before prepending the directory.
That's the cause why cmd /c myBatch.bat works, as then myBatch.bat is called without quotes.
You could also start the batch with a full qualified path, then it also works.
Or you save the full path in your batch, before changing the directory.
A small test.bat can demonstrate the problems of cmd.exe
#echo off
setlocal
echo %~fx0 %~fx1
cd ..
echo %~fx0 %~fx1
Call it via (in C:\temp)
test test
The output should be
C:\temp\test.bat C:\temp\test
C:\temp\test.bat C:\test
So, cmd.exe was able to find test.bat, but only for %~fx0 it will prepend the start directory.
In the case of calling it via
"test" "test"
It fails with
C:\temp\test C:\temp\test
C:\test C:\test
cmd.exe isn't able to find the batch file even before the directory was changed, it can't expand the name to the full name of c:\temp\test.bat
EDIT: FixIt, retrieve the fullname even when %~0 has quotes
There exists a workaround with a function call.
#echo off
echo This can be wrong %~f0
call :getCorrectName
exit /b
:getCorrectName
echo Here the value is correct %~f0
exit /b
Command line interpreter cmd.exe has a bug in code on getting path of batch file if the batch file was called with double quotes and with a path relative to current working directory.
Create a directory C:\Temp\TestDir. Create inside this directory a file with name PathTest.bat and copy & paste into this batch file the following code:
#echo off
set "StartIn=%CD%"
set "BatchPath=%~dp0"
echo Batch path before changing working directory is: %~dp0
cd ..
echo Batch path after changing working directory is: %~dp0
echo Saved path after changing working directory is: %BatchPath%
cd "%StartIn%"
echo Batch path after restoring working directory is: %~dp0
Next open a command prompt window and set working directory to C:\Temp\TestDir using the command:
cd /D C:\Temp\TestDir
Now call Test.bat in following ways:
PathTest
PathTest.bat
.\PathTest
.\PathTest.bat
..\TestDir\PathTest
..\TestDir\PathTest.bat
\Temp\TestDir\PathTest
\Temp\TestDir\PathTest.bat
C:\Temp\TestDir\PathTest
C:\Temp\TestDir\PathTest.bat
Output is four times C:\Temp\TestDir\ as expected for all 10 test cases.
The test cases 7 and 8 start the batch file with a path relative to root directory of current drive.
Now let us look on results on doing the same as before, but with using double quotes around batch file name.
"PathTest"
"PathTest.bat"
".\PathTest"
".\PathTest.bat"
"..\TestDir\PathTest"
"..\TestDir\PathTest.bat"
"\Temp\TestDir\PathTest"
"\Temp\TestDir\PathTest.bat"
"C:\Temp\TestDir\PathTest"
"C:\Temp\TestDir\PathTest.bat"
Output is four times C:\Temp\TestDir\ as expected for the test cases 5 to 10.
But for the test cases 1 to 4 the second output line is just C:\Temp\ instead of C:\Temp\TestDir\.
Now use cd .. to change working directory to C:\Temp and run PathTest.bat as follows:
"TestDir\PathTest.bat"
".\TestDir\PathTest.bat"
"\Temp\TestDir\PathTest.bat"
"C:\Temp\TestDir\PathTest.bat"
The result for second output for the test cases 1 and 2 is C:\TestDir\ which does not exist at all.
Starting the batch file without the double quotes produces for all 4 test cases the right output.
This makes it very clear that the behavior is caused by a bug.
Whenever a batch file is started with double quotes and with a path relative to current working directory on start, %~dp0 is not reliable on getting the path of batch file when current working directory is changed during batch execution.
This bug is also reported to Microsoft according to Windows shell bug with how %~dp0 is resolved.
It is possible to workaround this bug by assigning the path of the batch file immediately to an environment variable as demonstrated with the code above before changing the working directory.
And then reference the value of this variable wherever path of batch file is needed with using double quotes where required. Something like %BatchPath% is always better readable as %~dp0.
Another workaround is starting the batch file always with full path (and with file extension) on using double quotes as class Process does.
Each new line in your batch called by your ProcessStart is independently considered as a new cmd command.
For example, if you give it a try like this:
echo %~dp0 && CD Arvind && echo %~dp0
It works.