The error I am receiving upon executing my code is: 'ArgumentException was unhandled. Illegal characters in path.'
I am using the following code to access my .xml file.
string appPath = Path.GetDirectoryName(System.Environment.CommandLine);
FileInfo fi = new FileInfo(appPath + #"\Books.xml");
I am doing this for a console application, as opposed to a WinForm. I have been exhaustively googling, as well as searching SO, for some time.
This is part of a homework project. This is the only problem I am running into however.
string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
FileInfo fi = new FileInfo(Path.Combine(appPath, "Books.xml"));
System.Environment.CommandLine does not return a path - it returns the value of the command line that was executed to run the application.
You probably need to use Assembly.GetExecutingAssembly().Location (as Furqan Safdar posted in his answer) instead.
The format of the EXE path returned by CommandLine is funky, so you need to do something like this:
string appPath = Path.GetDirectoryName(System.Environment.CommandLine.Trim('"', ' '));
That should work.
Use this code to get application directory:
var rootDirectory = AppDomain.Current.BaseDirectory;
Good luck!
Related
I have been looking all over but cannot find a definitive answer/solution, or any solution I try fails. I am making a WinFormApp that calls an embedded .vbs file to script a program I use at work. This is what my Project Solution looks currently:
Project Solution
The test.vbs file is set as an embedded resource in its file properties. Here is the different code I have tried to use to run the script from the form:
private void button1_Click(object sender, EventArgs e)
{
string path = Path.Combine(Path.GetTempPath(), "test.vbs");
File.WriteAllBytes(path, Properties.Resources.Test);
Process.Start(path);
string path2 = Path.Combine(Path.GetTempPath(), "test.vbs");
System.Diagnostics.Process.Start(#"cscript //B //Nologo " + path2 + "");
}
Here is what my test.vbs file is:
dim thing
thing = "It did something!"
Wscript.Echo thing
The test.vbs file is primarily meant as a proof of concept to make sure I can at least run a .vbs file. The test.vbs file compiles fine outside of the WinForm.
Most of the time I receive 'The system cannot find the file specified' as the error message. I have read that it may be easier to just convert my .vbs file to C# but they are GUI scripting for SAP and all of SAP's libraries seem primarily set us for .vbs files.
I am still relatively new to C# so I may be way off with this so please tell me if I am. If there is another question that fixes my issue please link it.
Thank you for your time!
EDIT #1 Code compiles and seems to run.
string path2 = Path.Combine(Path.GetTempPath(), "test.vbs");
var startInfo = new ProcessStartInfo
{
WorkingDirectory = "" + path2 + "",
FileName = #"cscript"
};
However the script does not seem to be outputting to the cmd...
Your process start command is incorrect. Here is the correct version
System.Diagnostics.Process.Start("cscript", #"//B //Nologo " + path2 + "");
I'm trying to put a local html location address to the web browser in my C# application but always failed. I'm using debug mode now so the html files had already copied into my Debug folder because i put copy always in the copy to output option.
Below is my code:
string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
string filePath = Path.Combine(appPath, "index.html");
webBrowser1.Navigate(new System.Uri(#"file://"+ filePath));
There always this error coming out using that way:
An unhandled exception of type 'System.UriFormatException' occurred in System.dll
Any idea what went wrong?
Its a bit unclear but try this out. Hope this may help.
webBrowser1.Navigate(new Uri(#"your File Name"))
Or
webBrowser1.Navigate(new Uri(AppDomain.CurrentDomain.BaseDirectory == "\\File Name")
Edit:
May be this causing error,
webBrowser1.Navigate(new System.Uri("#" filePath + "file://"));
You just need to change your code slightly - here is the correct syntax:
string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
string filePath = Path.Combine(appPath, "index.html");
webBrowser1.Navigate(new System.Uri(filePath));
The issue is that CodeBase returns the path in URI format already so you do not need to add the additional the "file://" to the path.
I'm creating an extension for visual studio 2012 and am having a hard time finding the location of the arbitrary file that the extension is running behind. Does anyone have a good way of doing this through the extension? Maybe with reflection or some other sort of Path method?
You can do this:
Assembly.GetExecutingAssembly().Location
Then you need to look at the the functions in Path to find the directory. I think its one of these:
Path.GetDirectoryName
Path.GetPathRoot
I used the path extensions
Works great on https://dotnetfiddle.net/
using System.IO;
var path = "/test/test2/test.txt";
Console.WriteLine($"GetFileName {Path.GetFileName(path)}");
Console.WriteLine($"GetFullPath {Path.GetFullPath(path)}");
Console.WriteLine($"GetDirectoryName {Path.GetDirectoryName(path)}");
// correct exact path without filename
Console.WriteLine($"dirPath {path.Substring(0, path.Length - Path.GetFileName(path).Length)}");
/*
Prints:
GetFileName test.txt
GetFullPath /test/test2/test.txt
GetDirectoryName /test/test2
dirPath /test/test2/
*/
Note
the path separator has to be native to your machine. E.g. /test/test2/test.txt won't work on windows while \test\test2\test.txt will
string executingtitle = _applicationObject.Solution.FullName;
string[] title = executingtitle.Split( ',' );
string filename = title[0];
string filepath = Path.GetFullPath(filename);
One of my co-workers helped me out. Here's the code for future reference.
I have got this read file code from microsoft
#"C:\Users\computing\Documents\mikec\assignment2\task_2.txt"
That works fine when im working on it, but when i am to hand in this assignment my lecturer isn't going to have the same directory as me.
So i was wondering if there is a way to read it from just the file the program is held in?.
I was thinking i could add it as a resource but im not sure if that is the correct way for the assignment it is meant to allow in any file.
Thanks
You can skip the path - this will read file from the working directory of the program.
Just #"task_2.txt" will do.
UPDATE: Please note that method won't work in some circumstances. If your lecturer uses some automated runner (script, application whatsoever) to verify your app then #ken2k's solution will be much more robust.
If you want to read a file from the directory the program is in, then use
using System.IO;
...
string myFileName = "file.txt";
string myFilePath = Path.Combine(Application.StartupPath, myFileName);
EDIT:
More generic solution for non-winforms applications:
string myFilePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), myFileName);
If it is a command line application, you should take the file name as a command line argument instead of using a fixed path. Something along the lines of;
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Parameters are not ok, usage: ...");
return;
}
string filename = args[0];
...
...should let you get the filename from the command.
You could use the GetFolderPath method to get the documents folder of the current user:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
and to exemplify:
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = Path.Combine(myDocuments, #"mikec\assignment2\task_2.txt");
// TODO: do something with the file like reading it for example
string contents = File.ReadAllText(file);
Use the relative path.
you can put your file inside the folder where your application resides.
you can use Directory.GetCurrentDirectory().ToString() method to get the current folder of the application in. if you put your files inside a sub folder you can use
Directory.GetCurrentDirectory().ToString() + "\subfolderName\"
File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\fileName.extension")
StreamReader file = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + ""));
string fileTexts = file.ReadToEnd();
I'm creating a simple .NET console application where I want to save a file in a folder that's part of the root project, like so: SolutionName.ProjectName\TestData\. I want to put test.xml into the TestData folder. However, when I go to save my XDocument, it saves it to SolutionName.ProjectName\bin\x86\Debug Console\test.xml.
What do I need to do to save or retrieve the file in a folder that is a child of project directory?
Your console application is, once compiled, not really related to your Visual Studio solution anymore. The best way is probably to simply 'feed' the output path to your application as an command line argument:
Public Sub Main(args as String())
' don't forget validation: handle situation where no or invalid arguments supplied
Dim outputFile = Path.Combine(args(0), "TestData", "test.xml")
End Sub
Now you can run your application like so:
myapp.exe Path\To\SolutionFolder
I've seen this before but never actually tried it out. Did a quick search and dug this up:
System.AppDomain.CurrentDomain.BaseDirectory
Give that a shot instead of Application.StartupPath for your console app.
You can use the System.IO namespace to get your directory relative to your exe:
var exeDirectory = Application.StartupPath;
var exeDirectoryInfo = new DirectoryInfo(exeDirectory);
var projectDirectoryInfo = exeDirectoryInfo.Parent.Parent.Parnet; // bin/x86/debug to project
var dataPath = Path.Combine(projectDirectoryInfo.FullName, "TestData");
var finalFilename = Path.Combine(dataPath, "test.xml");