C# String Filepath Question - c#

I am trying to set a filepath for a SoundPlayer object
If I have a sounds folder in my main project folder. How do I go about sending
Soundplayer test = new Soundplayer("Sounds/Fireball.wav");

Where the file is relative to your main project is not important. What's important is where will the sound file be relative to your application at deployment / debug time. If it will have the same relative path as that of the main .exe path then you can use the following.
var root = typeof(Program).Assembly.Location;
var soundPath = Path.Combine(root, #"sounds\Fireball.wav");
var test = new SoundPlayer(soundPath);

Have you tried the path as #"Sounds\Fireball.wav"?

If you are running out of Visual Studio, the current working directory will be bin\Debug, so the file in question would need to be in bin\Debug\Sounds\Fireball.wav.
Also, as others have mentioned, you should use backslash \ rather than forwardslash /

Related

How to get path of a specific folder inside solution

I want to get the path of a specific folder inside the solution.
Ive tried to find answers on stack overflow, but i guess my concentration is already near the end and i cant find a real usefull answer.
Here is the folder i want (KeePassFiles):
I had those 2 files on the desktop before and reading them worked. But now i have to add those files into one of the solution folder and i only want to get the path for that.
It should work for different users who download that project.
My code right now for the desktop solution is:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var dbpath = #$"{desktopPath}\KeePassDatabase\Database.kdbx";
var keypath = #$"{desktopPath}\KeePassDatabase\Database.key";
Now it should be something like:
string solutionKPPath = Environment.GetFolderPath(path for solution);
var dbpath = #$"{solutionKPPath}\KeePassFiles\Database.kdbx";
var keypath = #$"{solutionKPPath}\KeePassFiles\Database.key";
Environment.CurrentDirectory will return the Debug directory or the Release directory depending on your run configuration. As far as I know, there is no easy way to get a specific folder or file in your solution. The best solution I could think of is using something like the following to get the solution directory:
public static DirectoryInfo TryGetSolutionDirectoryInfo(string currentPath = null)
{
var directory = new DirectoryInfo(
currentPath ?? Directory.GetCurrentDirectory());
while (directory != null && !directory.GetFiles("*.sln").Any())
{
directory = directory.Parent;
}
return directory;
}
And then use that path to dig into your folders and find the specific file you're looking for using something like Path.Combine(...).
In your case, don't pass any parameters to this method if you want it to retrieve the Debug/Release directory and search up from there
Edit: Note that this will actually not work for production since there will be no .sln file to find. As suggested by the comments on your question, you should configure your project to copy the necessary files into the output folder and therefore Environment.CurrentDirectory will do the trick
I think you should not get the files from the project source, you should copy them to the output during build and then get them from output location.
I would recommend to use "Copy to Output directory= Copy Allways" and than identify the "Execution Path" by use of AppDomain.CurrentDomain.BaseDirectory or Assembly.GetEntryAssembly().Location
If you using Unit Test, especially MS UnitTests it may be necessary to use `[DeploymentItem(#"\Shared\Keepassfiles\Database.kdbx")]

c# built-in function to get path of bin folder and not the application folder such as bin\Debug or bin\Release

We can get path of an application directory as follows. But this gives us the ...\bin\Debug or ...\bin\Release based on debug of release mode of the app. Question: How can we get the path of bin folder WITHOUT doing string manipulation - i.e. is there a built-in function for it?
string path = AppDomain.CurrentDomain.BaseDirectory;
No, there is no function like that because it is not necessary that the bin folder be always there.
AppDomain.CurrentDomain.BaseDirectory returns the current directory from where your code is executing. This is by default ...\bin\Debug (or ...\bin\Release) when you are running from Visual Studio, but that would not be the case always.
If your aim is to go one level up from current base directory without string manipulation, you can try something like this (as answered here)
string dirName = AppDomain.CurrentDomain.BaseDirectory; // Starting Dir
FileInfo fileInfo = new FileInfo(dirName);
DirectoryInfo parentDir = fileInfo.Directory.Parent;
string parentDirName = parentDir.FullName; // Parent of Starting Dir

How get file from a directory using relative path?

I am pretty new in C# and I am finding some difficulties trying to retrieve a jpg file that is into a directory of my project.
I have the following situation:
I have a Solution that is named MySolution, inside this solution there are some projects including a project named PdfReport. Inside this project there is a folder named Shared and inside this folder there is an header.jpg file.
Now if I want to obtain the list of all files that are inside the Shared directory (that as explained is a directory inside my project) I can do something like this:
string[] filePaths = Directory.GetFiles(#"C:\Develop\EarlyWarning\public\Implementazione\Ver2\PdfReport\Shared\");
and this work fine but I don't want use absolute path but I'd rather use a relative path relative to the PdfReport project.
I am searching a solution to do that but, untill now, I can't found it. Can you help me to do that?
Provided your application's Executable Path is "C:\Develop\EarlyWarning\public\Implementazione\Ver2", you can access the PdfReport\Shared folder as
string exePath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string sharedPath = Path.Combine(exePath, "PdfReport\\Shared\\");
string[] filePaths = Directory.GetFiles(sharedPath);
Try to get the current folder by using this
Server.MapPath(".");
In a non ASP.NET application but WinForms or Console or WPF application you should use
AppDomain.CurrentDomain.BaseDirectory
If you want root relative, you can do this (assuming C:\Develop\EarlyWarning is site root)
string[] filePaths = Directory.GetFiles(Server.MapPath("~/public/Implementazione/Ver2/PdfReport/Shared"));
Or if you want plain relative,
//assuming you're in the public folder
string[] filePathes = Directory.GetFiles(Server.MapPath("/Implementazione/Ver2/PdfReport/Shared"));
Root relative is usually best in my experience, in case you move the code around.
You can right click on your file header.jpg, choose Properties, and select for example the option Copy always on the property "Copy to Output Directory".
Then a method like this, in any class that belongs to project PdfReport:
public string[] ReadFiles()
{
return Directory.GetFiles("Shared");
}
will work well.
Alternatively, if you have files that never change at runtime and you want to have access to them inside the assembly you also can embed: http://support.microsoft.com/kb/319292/en-us

Load local HTML file in a C# WebBrowser

In my app I have a WebBrowser element.
I would like to load a local file in it.
I have some questions:
Where to place the HTML file (so that it will also be installed if a user executes the setup)
how to reference the file? (e.g. my guess is the user's installation folder would not always be the same)
EDIT
I've added the HTML file to my project.
And I have set it up so that it gets copied to output folder.
When I check it it is present when run: \bin\Debug\Documentation\index.html
However when I do the following I get a 'Page cannot be displayed' error in the webbrowser element.
I use the following code to try to display the HTML file in the Webbrowser.
webBrowser1.Navigate(#".\Documentation\index.html");
Do a right click->properties on the file in Visual Studio.
Set the Copy to Output Directory to Copy always.
Then you will be able to reference your files by using a path such as #".\my_html.html"
Copy to Output Directory will put the file in the same folder as your binary dlls when the project is built. This works with any content file, even if its in a sub folder.
If you use a sub folder, that too will be copied in to the bin folder so your path would then be #".\my_subfolder\my_html.html"
In order to create a URI you can use locally (instead of served via the web), you'll need to use the file protocol, using the base directory of your binary - note: this will only work if you set the Copy to Ouptut Directory as above or the path will not be correct.
This is what you need:
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));
You'll have to change the variables and names of course.
quite late but it's the first hit i found from google
Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:
//using System.IO;
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);
Note that the file:/// scheme does not work on the compact framework, at least it doesn't with 5.0.
You will need to use the following:
string appDir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, #"Documentation\index.html"));
Place it in the Applications setup folder or in a separte folder beneath
Reference it relative to the current directory when your app runs.
Somewhere, nearby the assembly you're going to run.
Use reflection to get path to your executing assembly, then do some magic to locate your HTML file.
Like this:
var myAssembly = System.Reflection.Assembly.GetEntryAssembly();
var myAssemblyLocation = System.IO.Path.GetDirectoryName(a.Location);
var myHtmlPath = Path.Combine(myAssemblyLocation, "my.html");
What worked for me was
<WebBrowser Source="pack://siteoforigin:,,,/StartPage.html" />
from here. I copied StartPage.html to the same output directory as the xaml-file and it loaded it from that relative path.
Windows 10 uwp application.
Try this:
webview.Navigate(new Uri("ms-appx-web:///index.html"));
Update on #ghostJago answer above
for me it worked as the following lines in VS2017
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));
I have been trying different answers from here, but managed to derive something working, here it is:
1- Added the page in a folder i created at project level named WebPagesHelper
2- To have the page printed by webBrowser Control,
string curDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
var uri = new Uri(curDirectory);
string myFile = Path.Combine(uri.AbsolutePath, #"WebPagesHelper\index.html");
Uri new_uri = new Uri(myFile);
i had to get the assembly path, create a first uri to get an absolute path without the 'file://' attached, next i combined this absolute path with a relative path to the page in its folder, then made another URI from the result.
Then pass this to webBrowser URL property webBrowser.URL = new_uri;

Open a text file with WPF

There is a text file that I have created in my project root folder. Now, I am trying to use Process.Start() method to externally launch that text file.
The problem I have got here is that the file path is incorrect and Process.Start() can't find this text file. My code is as follows:
Process.Start("Textfile.txt");
So how should I correctly reference to that text file? Can I use the relative path instead of the absolute path? Thanks.
Edit:
If I change above code to this, would it work?
string path = Assembly.GetExecutingAssembly().Location;
Process.Start(path + "/ReadMe.txt");
Windows needs to know where to find the file, so you need somehow specify that:
Either using absolute path:
Process.Start("C:\\1.txt");
Or set current directory:
Environment.CurrentDirectory = "C:\\";
Process.Start("1.txt");
Normally CurrentDirectory is set to the location of the executable.
[Edit]
If the file is in the same directory where executable is you can use the code like this:
var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(directory, "1.txt");
Process.Start(file);
The way you are doing this is fine. This will find the text file that is in the same directory as your exe and it will open it with the default application (probably notepad.exe). Here are more examples of how to do this:
http://www.dotnetperls.com/process-start
However, if you want to put a path in, you have to use the full path. You can build the full path while only caring about the relative path using the method listed in this post:
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/e763ae8c-1284-43fe-9e55-4b36f8780f1c
It would look something like this:
string pathPrefix;
if(System.Diagnostics.Debugger.IsAttached())
{
pathPrefix = System.IO.Path.GetFullPath(Application.StartupPath + "\..\..\resources\");
}
else
{
pathPrefix = Application.StartupPath + "\resources\";
}
Process.Start(pathPrefix + "Textfile.txt");
This is for opening a file in a folder you add to your project called resources. If you want it in your project root, just drop off the resources folder in the above two strings and you will be good to go.
You'll need to know the current directory if you want to use a relative path.
System.Envrionment.CurrentDirectory
You could append that to your path with Path
System.IO.Path.Combine(System.Envrionment.CurrentDirectory, "Textfile.txt")
Try using Application.StartupPath path as default path may point to current directory.
This scenario has been explained on following links..
Environment.CurrentDirectory in C#.NET
http://start-coding.blogspot.com/2008/12/applicationstartuppath.html
On a windows box:
Start notepad with the file's location immediately following it. WIN
process.start("notepad C:\Full\Directory\To\File\FileName.txt");

Categories