Edit: solution found, will note under image at the end of the question
After a bunch of research here on SO, I found that the way to open explorer with a selected file was:
Process.Start("explorer.exe", "/select, " + path);
However when I do this with controlled input, Explorer opens just its main window, however when I harcode the function call to the same value that's in the path variable (In my control test its a text file in C:\Temp) it works. So if I do the above when path is "C:\Temp\test.txt" It does't open explorer in the temp folder, however when I do:
Process.Start("explorer.exe", "/select, C:\\Temp\\test.txt");
It works perfectly, opening explorer and highlighting the file. What is happening here? Is there something wrong with the internal formatting on my string variable or something?
(Additionally, I ran into the same issue using the path variable to open a FileInfo. Hardcoded to the same value would work, but using the variable gave me a "the given path's format is not supported" exception")
Image showing that path and the harcoded value are the same:
The 2 explorer windows (cropped for Security) are the results of the 2 respective calls. The one with the variable shows te basic explorer main page. The one that's hardcoded shows the file selected as expected.
Edit: There was a hidden Left-To-Right Format character hidden in the front of the string.
public static class Program
{
static void Main()
{
Explore("C:\\Users\\art_g\\Desktop\\Sample.txt");
}
static void Explore(string path) =>
Process.Start("explorer.exe", "/select, " + path);
}
Works like a charm. Check your path string.
Related
I'm making a C# application which uses a text file located in the same directory as the application. when I start the app by double click, it runs without any problem. I want to start it using 4th mouse button but when I try, app makes error about finding the text file. My app is a simple launcher and i want it to run as easy as clicking a mouse button.
I defined text file path as below and I used public static to let other forms use the path and find the file too.
public static string list = System.IO.Directory.GetCurrentDirectory() + #"\list.txt";
Also tested:
public static string list = Environment.CurrentDirectory+ #"\list.txt";
The app and the text file are located in>> bin\Debug\
Error:
enter image description here
I use "Volume 2" Application (by Alexsandr Irza) to define functionality of 4th and 5th buttons of my mouse.I think it's so weird because running my app using double click makes no error and it can read the text file and write to it.
Please help me to fix it.
Don't use GetCurrentDirectory; that can change as your program runs.
If you want to find the directory of your executable, use
var path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location
);
To get the path of a file in the same directory as your executable:
var filePath = System.IO.Path.Combine(path, "list.txt");
How about something like:
string path = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\'));?
My application consists of a TreeView a RichTextBox and a Button.
The TreeView displays contents(directories, folders and files) of my system.
The Button when pressed is supposed to take the selected file from the TreeView and display it in the RichTextBox.
I have used the following code:
private void button_Click(object sender, EventArgs e)
{
string a = TreeView.SelectedNode.FullPath;
MessageBox.Show(a); //To check if it's taking the correct path
richTextBox1.LoadFile(a, RichTextBoxStreamType.PlainText);
}
The value in the string a is correct, that is TreeView.SelectedNode.FullPath returns the correct path which I confirm with the MessageBox.
However there is a runtime exception in the richTextBox1.LoadFile(a, RichTextBoxStreamType.PlainText) line.
It appends the path of the Debug folder before the actual selected file path(shown in the image), which leads to an exception.
All the files are stored locally.
How can I solve this problem?
It is because your tree nodes contains relative path to item instead of absolute.
How to prevent it? At first, you should store the full path (include drive name) in FullPath property.
If the path starts with the folder name, application tries to get the inner folder of current active folder (Debug). If the path starts with \ - app will seek the file in the root folder of current drive, if the path starts with drive name D:\ - app will seek the file on this drive. So, in your case, it will be better to pass absolute path always, it will exclude ambiguity while searching the file.
If the file should be stored relatively to the executive file, you should add some ..\ as prefix - it stands for 'going one level upper'
You can read this to get more familiar with windows pathname style.
After some research and trials I found the solution to this issue.
The reason behind this problem is that the code TreeView.SelectedNode.FullPath returns the path with an incorrect syntax.
Suppose the file you've selected in the TreeView has the path C:\Users\Admin\Desktop\test.txt
TreeView.SelectedNode.FullPath will return the path: C\Users\Admin\Desktop\test.txt which is syntactically incorrect i.e. it cannot be used directly in some other part of code.
The solution which I went for is, putting this output into a temporary string, and inserting :\\ in the 2nd place(1st index), thus making the syntax correct.(C:\\Users...)
Putting up the code I used just for reference:
private void button_Click(object sender, EventArgs e)
{
string a = TreeView.SelectedNode.FullPath.ToString();
string b = ":\\";
string c = a.Insert(1, b);
richTextBox1.LoadFile(c, RichTextBoxStreamType.PlainText);
}
Hope this helps. Thank you for the assistance I received while solving this problem.
Sorry for the likely noobish question, just starting to learn c#, and couldn't find anything that worked.
I'm making a text editor in c#, and so far it can open and save text files from inside the program with dialogs, but how can I make it load the text from a file that I open in windows explorer, outside of the editor, with the editor
Basically, I can already read from text files opened inside the editor, but how can i make it so that if I open a text file (and have the default program for opening text files set to my editor), it'll read it?
I saw something about getting the filename somehow and passing it as an argument, if that helps.
If I understood you correctly, you want to pass the filename/names as command line arguments ?
If you look at the Main, which starts the program you can see that it will store parameters in a string[] (string array) so if you pass arguments you can just check the args[] inside the program to get the parameters you sent in. Please ask more if you need more help !
UPDATED
As per your request if you open a file from windows explorer it will send the path of the file it to the Main method. So lets say you right click a file and choose to open it with your text editor. You have to use the path as I do below, and read the file's content. Then you can do whatever you want with the content.
class TestClass {
static void Main(string[] args) {
// Now you have all arguments in the string array
if (args.Length != 0) {
string pathToTextfile = args[0];
}
StreamReader textFile = new StreamReader(pathToTextfile);
string fileContents = textFile.ReadToEnd();
textFile.Close();
}
}
So you have a text editor coded in C#, and you want to be able to open a text file through double clicking on the file in Windows explorer. If so, basically 2 steps:
1. Your editor program must accept one argument as the file name. Carl had already given an example.
2. You need to associate *.txt files with your text editor. This could be done through editing Windows registry. please check What registry keys are responsible for file extension association
You can use the OpenFileDialog class to select a file to show in your program.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting path relative to the current working directory?
I have code in C# that includes some images from an absolute path to a relative so the image can be found no matter where the application fold is located.
For example the path in my code (and in my laptop for the image) is
C:/something/res/images/image1.jpeg
and I want the path in my code to be
..../images/image1.jpeg
So it can run wherever the folder is put, whatever the name of the C: partition is etc.
I want to have a path in my code which is independant of the application folder location or if it is in another partition, as long as it is in the same folder as the the rest of the solution.
I have this code:
try
{
File.Delete("C:/JPD/SCRAT/Desktop/Project/Resources/images/image1.jpeg");
}
catch (Exception)
{
MessageBox.Show("File not found:C:/Users/JPD/Desktop/Project/images/image1.jpeg");
}
This code only runs if the file and folder are in that certain path, (which is also the location of the code) I wish for that path to be relative so wherever I put the whole folder (code, files etc) the program will still work as long as the code (which is under project folder) is at the same location with the folder images... what should I do?
Relative paths are based from the binary file from which your application is running. By default, your binary files will be outputted in the [directory of your .csproj]/bin/debug. So let's say you wanted to create your images folder at the same level as your .csproj. Then you could access your images using the relative path "../../images/someImage.jpg".
To get a better feel for this, try out the following as a test:
1) create a new visual studio sample project,
2) create an images folder at the same level as the .csproj
3) put some files in the images folder
4) put this sample code in your main method -
static void Main(string[] args)
{
Console.WriteLine(Directory.GetCurrentDirectory());
foreach (string s in Directory.EnumerateFiles("../../images/"))
{
Console.WriteLine(s);
}
Console.ReadLine(); // Just to keep the console from disappearing.
}
You should see the relative paths of all the files you placed in step (3).
see: Getting path relative to the current working directory?
Uri uri1 = new Uri(#"c:\foo\bar\blop\blap");
Uri uri2 = new Uri(#"c:\foo\bar\");
string relativePath = uri2.MakeRelativeUri(uri1).ToString();
Depending on the set up of your program, you might be able to simply use a relative path by skipping a part of the full path string. It's not braggable, so J. Skit might be up my shiny for it but I'm getting the impression that you simply want to make it work. Beauty being a later concern.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
String relativePath = absolutePath.Substring(13);
You could then, if you need/wish, exchange the number 13 (which is an ugly and undesirable approach, still working, though) for a dynamically computed one. For instance (assuming that the directory "HereWeStart", where your relative path is starting, is the first occurrence of that string in absolutePath) you could go as follows.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
int relativePathStartIndex = absolutePath.IndexOf("HereWeStart");
String relativePath = absolutePath.Substring(relativePathStartIndex);
Also, your question begs an other question. I'd like to know how you're obtaining the absolute path. Perhaps there's an even more clever way to avoid the hustle all together?
EDIT
You could also try the following approach. Forget the Directory class giving you an absolute path. Go for the relative path straight off. I'm assuming that all the files you're attempting to remove are in the same directory. If not, you'll need to add some more lines but we'll cross that bridge when we get there.
Don't forget to mark an answer as green-checked (or explain what's missing or improvable still).
String
deletableTarget = #"\images\image1.jpeg",
hereWeAre = Environment.CurrentDirectory;
MessageBox.Show("The taget path is:\n" + hereWeAre + deletableTarget);
try
{ File.Delete(hereWeAre + deletableTarget); }
catch (Exception exception)
{ MessageBox.Show(exception.Message); }
Also, please note that I took the liberty of changing your exception handling. While yours is working, it's a better style to rely on the built-in messaging system. That way you'll get more professionally looking error messages. Not that we ever get any errors at run-time, right? ;)
I have a web browser in C# that I want to make navigate to a path (html file) on my local pc.
I tried using this:
if (File.Exists(Path + b.HTML))
{
browserCom1.Navigate(Path + b.HTML);
}
The file Exists, but the browser is keep opening an error of Internet Explorer: "cannot find file:///(my path here)"
It is weird because the file is correct. for example if I use:
System.Windows.Forms.OpenFileDialog browseFile = new
System.Windows.Forms.OpenFileDialog();
browseFile.ShowDialog();
String path = browseFile.FileName;
browserCom1.Navigate(path);
and I select the same file that it tried navigating to before, it works.
If I print the above brwseFile File Name to Console(which is the same as my Path+b.HTML by the way), and copy-paste it into the Navigate(...) Function (changing each '\' to '//') it Doesn't work.
I have no Idea what to do.
I tried something else like:
String path=(File.Open(Path + b.HTML, FileMode.Open).Name);
browserCom1.Navigate(path);
but the application keep getting freezed upon this.
I also tried with new URI(path) and all.
How can I simpley navigate to a HTML file on my computer?
You have http slashes, but should have file system slashes, like c:\something\something.html
I had the same problem. Resolved when I cleaned for double \\ in the code.
If that's not your problem - your problem may be some else problem related to parsing from string to uri.
my path was like this: c:\users\someone1\\myFolder\protocol.htm