I wanted to start a .exe file in a different folder but I wanted other people to also use it and I've been trying many things but it just keeps opening the file that the program that I'm creating is in. (I'm new to c#).
My ex of ^: \Desktop\VSCheatDetector\CheatDetector.exe(the program) and another regular file named viper_screenshare_tool and it has CheatDetector.exe (which I want to open when I click a certain button)
Code:
private void cheat_smasher_click(object sender, EventArgs e)
{
string dir = AppDomain.CurrentDomain.BaseDirectory;
Process.Start(dir, "vipers_screenshare_tool\\CheatDetector.exe");
}
You don't want to use AppDomain.CurrentDomain.BaseDirectory; - I'd suggest using App.config or something like that instead.
Related
I'm developing a retro-style game in C# .NET-Framework, and I would like to use different sounds and music in my game. But I have a problem. The original System.Windows.Media.SoundPlayer doesn't support 2 (or more) sounds being played. When one starts, it stops the active one.
I'm looking for a solution that can play different audio at the same time. I tried threading the different SoundPlayers to different threads, but that wasn't a good solution for me (+ it didn't work).
I read about System.Windows.Media.MediaPlayer, and the different controls that you could use with it. This instantly had me interested, especially after I read that you could play different sounds at once.
But trying to use the MediaPlayer in my game, it throws an error, because the URL isn't spelled correct. Here is my code:
using System.Windows.Media;
MediaPlayer Sound = new MediaPlayer();
MediaPlayer BackgroundMusic = new MediaPlayer();
private void Form1_Load(object sender, EventArgs e)
{
Sound.Open(new Uri("Text1.wav"));
BackgroundMusic.Open(new Uri("BackgroundMusicMix.wav"));
}
private void BtnSound_Click(object sender, EventArgs e)
{
Sound.Play();
}
private void BtnBackgroundSound_Click(object sender, EventArgs e)
{
BackgroundMusic.Play();
}
The .wav-files are here located in the \bin\debug folder of my solution, because the SoundPlayer also gets it's sounds from there. I am aware of the fact that you can always put in the full filepath, but the project is being edited by multiple people, so we need the sounds to be located in the solution folder (relative URL).
SO my question is: what is the correct spelling for relative URL? Or even better, is there a simpler method to play 2 sounds simultaneously?
The issue with the "relative URL" you're seeking is that it'd be relative to what? This is a compiled application, not a web page, so neither Uri nor MediaPlayer can assume the answer to that.
That you don't want to hard-code an absolute path doesn't mean you can't construct one at runtime, though. You can use the Assembly.GetExecutingAssembly() method to get the absolute path to your application...
string executableFilePath = Assembly.GetExecutingAssembly().Location;
...and then use the Path class to turn that into an absolute path to your audio file...
string executableDirectoryPath = Path.GetDirectoryName(executableFilePath);
string audioFilePath = Path.Combine(executableDirectoryPath, "BackgroundMusicMix.wav");
...from which you can create an absolute file URL...
Uri audioFileUri = new Uri(audioFilePath);
See Convert file path to a file URI? for some of the peculiarities to consider when constructing a Uri from a filesystem path like that.
By the way, as far as alternatives, I've not used this myself so I don't know how suited it is for what you're doing, but I know NAudio is a thing that exists.
I am new to C# and I have normally built windows forms using VB and was able to use one code to open any embedded file I added to my "Resources". As far as C# I have looked online for hours and have yet to find anything that worked. Please assist in any way that you can.
I have a Windows Form that will have a single button that will be assigned to open a particular file I have added to the "Resources" folder. Usually I would use the following code to have a Button_Click to load an exe, doc or pdfile. I am looking for something similar for C#.
VB Code:
IO.File.WriteAllBytes(My.Computer.FileSystem.SpecialDirectories.Temp & "\IEResetConfigure.exe", My.Resources.IEResetConfigure)
Process.Start(My.Computer.FileSystem.SpecialDirectories.Temp & "\IEResetConfigure.exe")
Simply write your resource file to temporary directory and run the file
using System;
using System.IO;
using System.Diagnostics;
// ...
byte[] resourceFile = Properties.Resources.Newspaper_PC_13_12_2013;
string destination = Path.Combine(Path.GetTempPath(), "Newspaper_PC_13_12_2013.pdf");
System.IO.File.WriteAllBytes(destination, resourceFile);
Process.Start(destination);
Example of my comment
using System;
using System.IO;
using System.Diagnostics;
using System.Threading.Tasks;
// ...
static void Main(string[] args)
{
byte[] resourceFile = Properties.Resources.Newspaper_PC_13_12_2013;
string destination = Path.Combine(Path.GetTempPath(), "Newspaper_PC_13_12_2013.pdf");
File.WriteAllBytes(destination, resourceFile);
Process.Start(destination);
AutoDelete(2000, destination);
Console.Write("Press any key to quit . . . ");
Console.ReadKey(true);
}
static async void AutoDelete(int milliseconds, string destination)
{
while (File.Exists(destination))
{
await Task.Delay(milliseconds);
try
{
File.Delete(destination);
}
catch
{
continue;
}
}
}
For anyone still looking, Here is a way of opening an "embedded" file. I'd love for someone to correct me below on a better way.
The first part is to make sure your file is added to your project in the bin\debug folder.
I then used this code to call it
private void button1_Click(object sender, EventArgs e)
{
//Place file in .\bin\Debug folder of project
string filename = "YourFileName.pdf";
System.Diagnostics.Process.Start(filename);
For full Disclosure this whole part has been stolen from
(Opening a .pdf file in windows form through a button click)
I did however run into an issue where after the first build that didn't work for me. So when I created the setup project I added the "Project Output" and then added in my pdf via "add file" to the application folder.
That has continued to work flawlessly for me since.
This is my first post on Stack Overflow, so please let me know if I misunderstood any rules or could improve. Thank you and I hope this helped!
In WPF application where I have included some files in resources, I want to execute them on a button click. How do I specify a path in Process.Start().
private void button1_Click_2(object sender, RoutedEventArgs e)
{
Process.Start("test.txt");
}
Or is there any other way?
private void button1_Click_2(object sender, RoutedEventArgs e)
{
string path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\test.txt";
if (File.Exists(path))
{
Process.Start(new ProcessStartInfo(path));
}
else
{
MessageBox.Show("No file found"+path);
}
I added a message box and it showed No files found. :(
EDIT:
I Tried to check the path after publishing and this what i got.
No File Found With a Path - C:\Users\Administrator\AppData\Local\Apps\2.0... test.txt
Before I published the Application I got a path which id
No File Found at ..project..\bin\Debug\test.txt which is obvious since my Resource file not included there its Under a Resource Folder and not Debug when i add a test file in debug it open without any problem.
Can someone Help throwing some light on this case.
EDIT:
I want to open a file from Resource directory # C:\Users\Administrator\Documents\Visual Studio 2010\Projects\FastFix\FastFix\Resources Which would be included in my project when i am going to publish it is going to run as a standalone application without installation.
use this
string path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\test.txt";
if (File.Exists(path))
{
Process.Start(new ProcessStartInfo(path));
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
string[] files = new string[] { #"C:\directory\of\file\to\copy.txt" };
this.DoDragDrop(new DataObject(DataFormats.FileDrop,files), DragDropEffects.Copy);
}
This is the code that i used.
Well, it works well, but want to get the directory of the copied file.
How can I do this?
Using that the static Path class of System.IO,you can extract the path of directory
Path.GetDirectoryName(#"C:\Users\JNK\Desktop\2136D.png");
All you got is the return value of DoDragDrop() to see if the drop actually happened. What the receiving app did with the file is something you cannot find out. Could be anything, including not copying the file at all. A random example is only opening the file in a text editor, the behavior of VS and Notepad.
Note how the example you gave only drags from the desktop, not to the desktop. Use FileBrowserDialog if you need to know where the user wants to copy a file.
I have a program I have written in C#, which loads an image with Image.FromFile, and it loads the image successfully every time. However, when you drag and drop another file on the executable, like you are giving the program the command line argument of the file, and the file is not in the same folder as the executable, the program crashes because it says the path to the file does not exist, even though it does.
I think that by dropping a file on the executable, it's changing the path it's loading images from somehow. How can I fix this problem?
Your program would be started with a different Environment.CurrentDirectory. Always make sure you load files with an absolute path name (i.e. don't use Image.FromFile("blah.jpg")).
To get the absolute path to a file that's stored in the same directory as your EXE, you could use Application.StartupPath for example. Or Assembly.GetEntryAssembly().Location if you don't use Windows Forms.
It depends on how you are initiating the file drag outside of your application. If you click and drag a file from Windows Explorer, the full absolute path name is included in the drop. In this case the following code shows the filename and performs a drop of the file's contents into a textbox:
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
var objPaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
if (objPaths != null && objPaths.Length > 0 && File.Exists(objPaths[0]))
{
MessageBox.Show(string.Format("Filename: {0}", objPaths[0]));
using (TextReader tr = new StreamReader(objPaths[0]))
textBox1.Text = tr.ReadToEnd();
}
}
}
So let us know more about your drag source. Most likely you will have to modify your source to drag the absolute path, or somehow determine the full path from the relative path in the drag data.
Also, your program should never crash due to bad data. Either check for the required conditions, or use a try/catch block around the necessary code.