I made a small program in c# with a button that is supposed to open another .exe file.
It works fine if I use:
private void start_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start(#"path to file");
}
But not if I want it to run an .exe from the same folder, i basically wanted something like:
private void start_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Process.Start(#"program.exe");
}
What am I missing, I've tried a solution from this website:
var startIngo = new ProcessStartInfo();
startIngo.WorkingDirectory = // working directory
// set additional properties
Process proc = Process.Start(startIngo);
But Visual c# doesn't recognize "ProcessStartInfo" at all...
What your looking for is:
Application.StartupPath
It will return the startup path that your executable was started in.
If you are using WPF, try this instead:
String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
You can do:
var startupPath = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetEntryAssembly().Location);
var programPath = System.IO.Path.Combine(startupPath, "program.exe");
System.Diagnostics.Process.Start(programPath);
ProcessStartInfo is in the System.Diagnostics namespace - you need to import that namespace at the top of your cs file using a using System.Diagnostics; statement for the compiler to recognise ProcessStartInfo without specifying the namespace explicitly where you use the class.
You could also try System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
To get your local path. For example
//in your imports/using section
using System.IO
using System.Reflection
using System.Diagnostics;
//in your code to execute
Process.start(Path.GetDirectoryName(Aseembly.GetExecutingAssembly().GetName().CodeBase) + "\\program.exe")
There are two cases:
The application was started directly - start up path can be extracted from the command-line.
The application was started indirectly - e.g. from a unit-test, start up path can not be extracted from the command-line, however you can read it from the current directory into a static variable during the start-up (before the user has a chance to change it (e.g. using a file open/save dialog)).
Related
I followed Joe's idea on how to use CommonOpenFileDialog to open a folder / file here
I've installed the package Microsoft.WindowsAPICodePack-Shell in my project and included this line as well: using Microsoft.WindowsAPICodePack.Dialogs;
The code:
private void Button_Click(object sender, RoutedEventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
dialog.Multiselect = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
MessageBox.Show("You selected: " + dialog.FileName);
}
}
However, there are some methods / attributes that I could not use.
I screenshotted the errors I got: errors
Is there an updated documentation on how to use the CommonOpenFileDialog package so that I can refer to it?
This works, you must simply install it using Install NuGet packages. Search for WindowsAPICodePack-Shell, then install it for your project.
Next, make sure the Microsoft.WindowsAPICodePack and Microsoft.WindowsAPICodePack.Shell DLLs are visible in the dependency list.
Make sure there is using Microsoft.WindowsAPICodePack.Dialogs; declaration in the file where you are using the control.
If you are using it in a console application, add [STAThread] right above the static void Main(string[] args).
You could use the System.Windows.Forms.OpenFileDialog for opening files, it contains the properties InitialDirectory and Multiselect.
For opening folders, you could use System.Windows.Forms.FolderBrowserDialog . With this class, you would need to use the property RootFolder to choose where the browsing starts from.
I'm new to C# and I have been trying to play a sound using SoundPlayer class. So in my solution in visual studio (2015 community), I created a folder called Music and drag'n'dropped a wav file there. In properties, I found the file path and then used in the SoundPlayer constructor. Right now, it's on the desktop.
My problem is that I'll be moving the actual program (it's just console app) to another computer (with different user name...which I don't know). So is there a way C# can determine the new location (directory) for the file so that I don't get an error?
SoundPlayer spPlayer = new SoundPlayer (#"C:\Users\tvavr\Desktop\Dango\mr_sandman.wav");
spPlayer.Play();
This is the code that works. Now, how am I supposed to change that path?
Thx for your answers.
use dynamic path as following :
SoundPlayer spPlayer = new SoundPlayer (Application.ExecutablePath +#"\mr_sandman.wav");
where Application.ExecutablePath will get your application folder dynamically
This is a design decision that only you can answer. When you write console applications that require you to load a file, you have several options
Option #1: Have the path specified in the argument list of the program when it is executed
Assume the name of your program is playsong, you run it like this:
playsong C:/path-to-music-file/song.wav
You get the name of the song file from the argument list of Main. The first item in args is the filename:
static void Main(string[] args) {
SoundPlayer spPlayer = new SoundPlayer(args[1]);
spPlayer.Play();
}
Option #2: Access the song file by hard coded path
static void Main() {
SoundPlayer spPlayer = new SoundPlayer("C:/playsong/songs/song.wav");
spPlayer.Play();
}
Option #3: Access the song file relative to the program location
static void Main() {
SoundPlayer spPlayer = new SoundPlayer(Application.ExecutablePath + "/songs/song.wav");
spPlayer.Play();
}
If you later want to change this into a Graphical User Interface (GUI) program, you would bring up the OpenFileDialog box which lets the user choose the file.
.NET has built-in tools to access locations like current user's desktop:
System.Environment.SpecialFolder.Desktop
If I feed Process.Start(); the parameters "Firefox", Notepad or "cmd" it runs those programs like their location is built in, but with other programs I have to specify the program's directory for it to work.
How does it automatically know where some programs located, and why only those programs and not others?
My code:
using System;
using System.Diagnostics;
namespace Testing
{
public class MainClass
{
static void Main()
{
Process.Start("Firefox"); // Works
Process.Start("Notepad"); // Works
Process.Start(#"C:\Users\user\Desktop\Steam"); // Works too
Process.Start("Steam"); // This line gives me "The System cannot find the file specified"(run-time error)
}
}
}
I think it depends on Environment variables in Windows.
or type PATH in cmd and observe paths, where *.exe files can be found automatically.
I have an ASP.Net website that references a class library. In the class library I need to read a file into memory.
At the top level of my class library there is a folder called EmailTemplateHtml containing the file MailTemplate.html that I want to read in.
How can I do this?
In Visual Studio, you can configure your library such that the file is copied into the build directory of any project that depends upon it. Then you can get the path to the build directory at runtime in order to read your file.
Step by step instructions, starting from a fresh solution:
Create your application project and your class library project.
Add a reference to the class library project from the application project via Properties->Add->Reference from the application's context menu in Solution Explorer:
Create the file in your class library project that you need to read, then set its Copy to Output Directory property to either Copy always or Copy if newer via the Properties pane in Solution Explorer:
From within either the class library project or your application (either will work with exactly the same code), reference your file relative to Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location). For example:
using System.Reflection;
using System.IO;
namespace MyLibrary
{
public class MyClass
{
public static string ReadFoo()
{
var buildDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filePath = buildDir + #"\foo.txt";
return File.ReadAllText(filePath);
}
}
}
(Note that back before .NET Core, you could use a file path relative to System.IO.Directory.GetCurrentDirectory() instead, but this doesn't work in a .NET Core application because the initial working directory for .NET Core apps is the source directory instead of the build directory, apparently because this was needed by ASP.NET Core.)
Go ahead and call your library code from your application code, and everything will work fine. e.g.:
using Microsoft.AspNetCore.Mvc;
using MyLibrary;
namespace AspCoreAppWithLib.Controllers
{
public class HelloWorldController : Controller
{
[HttpGet("/read-file")]
public string ReadFileFromLibrary()
{
return MyClass.ReadFoo();
}
}
}
using System.IO;
using System.Reflection;
public static string ExecutionDirectoryPathName()
{
var dirPath = Assembly.GetExecutingAssembly().Location;
dirPath = Path.GetDirectoryName(dirPath);
return Path.GetFullPath(Path.Combine(dirPath, "\EmailTemplateHtml\MailTemplate.html"));
}
If you want to find the path where the assembly is located; from within the assembly then use the following code:
public static string ExecutionDirectoryPathName
{
get
{
var dirPath = Assembly.GetExecutingAssembly().Location;
dirPath = Path.GetDirectoryName(dirPath);
return dirPath + #"\";
}
}
I am not sure what you mean by a folder in the class library but you can use the current working directory if you wish to build a path as follows:
System.IO.Directory.GetCurrentDirectory()
You can then use the Path.Combine() method to build file paths.
You can add a Static class in your class library with some static methods/properties to set. Set the values from Global.ascx.cs on start app method. Now you can get the values of class library.
Hope this makes clear.
Happy coding
I have a class library which is deployed on an ISP server to be consumed by an ASP.NET web service. I'd like to keep track of any errors and in this case the windows event log is inaccessible to me. So I thought I'd write to a txt file using the StreamWriter class. Problem is if I don't give an absolute path and just a file name it tries to write to C:\Windows\System32, and that's no good to me.
How can I tell it to use maybe the data directory or the application root? Any thoughts?
Use Server.MapPath to get a path relative to the web application.
using (FileStream fs = new FileStream(Server.MapPath("~/logs/logfile.txt"),
FileMode.Append)) {
//do logging here.
}
While some of the previous posters have suggested using reflection to get the executing assembly, I'm not sure whether or not that will net you the web application or the w3wp process. If it's the latter, you're still going to end up trying to write to the System32 folder.
Here is what I used to use, it's a little clunky but it gets the job done:
using System;
using System.Collections.Generic;
using System.Web.UI;
public static class Logger
{
private static readonly Page Pge = new Page();
private static readonly string Path = Pge.Server.MapPath("~/yourLogPath/Log.txt");
private const string LineBreaker = "\r\n\r======================================================================================= \r\n\r";
public static void LogError(string myMessage, Exception e)
{
const LogSeverity severity = LogSeverity.Error;
string messageToWrite = string.Format("{0} {1}: {2} \r\n\r {3}\r\n\r {4}{5}", DateTime.Now, severity, myMessage, e.Message, e.StackTrace, LineBreaker);
System.IO.File.AppendAllText(Path, messageToWrite);
}
}
I had this class in it's own project, separate from the website itself, and I used it in all of my other non website projects...
Edit:
Btw LogSeverity is just an enum I made up...
In my web product, in the web.config I specify an appSettings block like this:
<configuration>
<appSettings>
<add key="MyLogPath" value="LogPath" />
</appSettings>
</configuration>
which you can use from the code like
ConfigurationManager.AppSettings["MyLogPath"]
then you can have the installer configure it to wherever you want. you probably don't want the log files in your application directory.
Try checking out:
Application.StartupPath;
Here's a link to the docs
Gets the path for the executable file
that started the application, not
including the executable name.
string path = Application.StartupPath;
Note: you'll still need to add a file name.
You can find out the path of your executable by doing this:
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);