Open video file in C# - c#

I am new to C# and this might sound stupid, I did some research and I think I am confused.
I want my c# program to open a video file (c:\abc.mov), I have set the .mov files to open automatically with quick time player and I want the program to open the file with quick time player just like double clicking on that file.
When I use this code it does not do anything!
File.Open(#"c:\abc.mov", FileMode.Open);
Please help me?

You should use Process.Start instead. Here's the MSDN page on that.
You can specify which program you want to start with whetever arguments you need, like in this example.
Edit: Added another example. Thanks #DJBurb
Process.Start(#"c:\\abc.mov");
This code should open the .mov file with the default movie player associated with the .mov extension.

This will open your video file with the dafault video player
System.Diagnostics.Process.Start(filepath);

i believe that open() will open your file for editing for this current program, not actually opening the file with your system's default player

File.Open returns FileStream so you can read that file, instead you most definitely want to use Process.Start(#"c:\abc.mov");

private void buttonOpen_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog()==DialogResult.OK)
{
Process.Start(ofd.FileName);
}
}

Related

C# .NET MediaPlayer can't use relative URL

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.

How to use a Embedded file from Assembly for SoundPlayer contexts inside of a C# application

Hello Stack Overflow community,
I have been working on making a custom installer/launcher for the game I am making, it is currently in working in a non-portable context, however if I want to put it inside of a game for distribution, it must work inside of a portable context (i.e. it should not access the drive for any of it's own needs, only the other software's needs)/
At the current moment it loads a song from the drive to play, and as well loads the prerequisites for the game if the launcher has never been opened before or did not finish successfully. The files are all set to "EmbeddedResource" inside of SharpDevelop, and they are part of the final compiled script.
However, in the code's current context, the script still has to access the drive to do all of those functions, even when they are embedded into the final program.
The current code I have so far is below, "programpath" refers to the directory of which the file is being executed from, "MainText" is the main output window, which is better seen in this Stack Overflow question, and label1 is a debug line, that is only used to show the path of the current running command (will be removed when all the things are embedded).
public MainForm()
{
//Open Window
InitializeComponent();
CenterToScreen();
//Start song
System.Media.SoundPlayer player = new System.Media.SoundPlayer(programpath+"\\Resonance.wav");
player.PlayLooping();
this.Shown+=(s,e)=>{
if(File.Exists(programpath+"\\FirstLaunch.lic")&&File.ReadAllText(programpath+"\\FirstLaunch.lic").IndexOf("Installation Successful")>=0){
BackColor=System.Drawing.Color.OrangeRed;
MainText.BackColor=System.Drawing.Color.OrangeRed;
MainText.ForeColor=System.Drawing.Color.Aquamarine;
MainText.Text="Starting game..";
Process game = new Process();
//placeholder executable, will be finished game executable
game.StartInfo.FileName="D:\\UT2004\\System\\UT2004.exe";
game.StartInfo.ErrorDialog=true;
game.Start();
//stop playing music,
player.Stop();
//when game stops, close the launcher
game.WaitForExit();
Application.Exit();
}else{
//Start prerequisite installation
newLaunch();
}
};
}
//if the launcher has not been open before OR the last installation was not successful
void newLaunch(){
//Creates and makes a stream to the file
StreamWriter writer = new StreamWriter(programpath+"\\FirstLaunch.lic");
//Changing color scheme
BackColor=System.Drawing.Color.Chartreuse;
MainText.BackColor=System.Drawing.Color.Chartreuse;
MainText.ForeColor=System.Drawing.Color.Black;
MainText.Text="Configuring Prerequisites....\nInstalling DirectX";
//write to file about stage
writer.Write("Installing DirectX");
//start DirectX installer
Process prerequisite = new Process();
prerequisite.StartInfo.FileName=programpath+"\\dxwebsetup.exe";
prerequisite.StartInfo.ErrorDialog=true;
prerequisite.Start();
//debug line
label1.Text=programpath+"\\dxwebsetup.exe";
//wait for installer to finish and close
prerequisite.WaitForExit();
//remove refernce to DirectX installer
prerequisite.Close();
//write to file about stage
writer.WriteLine("...true");
//Changing color scheme
BackColor=System.Drawing.Color.DarkMagenta;
MainText.BackColor=System.Drawing.Color.DarkMagenta;
MainText.ForeColor=System.Drawing.Color.Yellow;
MainText.Text="Configuring Prerequisites....\nInstalling Microsoft VC++2015 Update RC3";
//write to file about stage
writer.Write("Installing VCRedist");
//start VC Redistributable installer
prerequisite.StartInfo.FileName=programpath+"\\vc_redist.x86.exe";
prerequisite.StartInfo.ErrorDialog=true;
prerequisite.Start();
//debug line
label1.Text=programpath+"\\vc_redist.x86.exe";
//wait for installer to finish and close
prerequisite.WaitForExit();
//remove reference to VC Redistributable installer
prerequisite.Close();
//write to file about stage
writer.WriteLine("...true");
writer.WriteLine("Installation Successful");
writer.Close();
//re-open launcher from open context
label1.Text=programpath+"\\ColorLoop.exe";
Process.Start(programpath+"\\ColorLoop.exe");
Application.Exit();
}
}
}
How do I get the program to play the music, and load the pre-requisites from itself and not from separate drive files inside the code. It is all already embedded, just not being used.
I finaly figured it out, so I am answering my own question in the hopes that people who are struggling in the future can figure it out.
Using the link provided by #Jimi for Accessing Resources in SharpDevelop, and scrolling down to the "Embedding Files directly" section, shows the context at which to access Embedded Resource. The thing to note here is that the return type of GetManifestStream(string) is a System.IO.Stream object.
This is important as we need SoundPlayer to accept a System.IO.Stream object some how. This can be done two ways, by using an overloaded constructor or Property of the SoundPlayer class. As defined by the MSDN page for the SoundPlayer Class.
However, when I tested this, I could not get the sound to play. Furthering my research, I found that Assembly.GetExecutingAssembly() has a accessible method named "GetManifestResourceNames()" that returns a string array of all the resources and their corrective names to access them. I was able to see the return by creating a Windows Form Label called "ExecutingAssem", and using the instructions from DotNetPerls to create a static method named "ConvertStringArrayToStringJoin()", but changing its seperator from "." to "|" to better read the assets.
With that in place the final program shows the list of embedded resources with the line:
ExecutingAssem.Text=ConvertStringArrayToStringJoin(Assembly.GetExecutingAssembly().GetManifestResourceNames());
And the final program appearing as:
Program showing all the resources in the corner
The interesting thing here is that the song resource (Resonance) is not actually a part of the Namespace, or MainForm...but rather its own name as the resource title.
With that missing information found, I needed to change the program from reading the drive to reading the manifest stream. Using the overloaded constructor that utilizes a System.IO.Stream object as a parameter instead of a string to a file location, I changed where the player object is initiated to use that constructor.
SoundPlayer player =new SoundPlayer(Assembly.GetExecutingAssembly().GetManifestResourceStream("Resonance"));
Finally the final application played the song with the ability to move the .exe file elsewhere and still be able to play the same song without "Resonance.wav" needing to be in the same directory.
private void button1_Click(object sender, EventArgs e)
{
SoundPlayer player = new SoundPlayer();
//Add TestSound.wav file to the built-in resource file Project>Properties>Resources.resx
player.Stream = Properties.Resources.TestSound;
//Add TestSound.wav file to a new resource file Resource1.resx
//player.Stream = Resource1.TestSound;
player.Play();
}

Opening an Excel file in C# using Process.Start

I'm trying to open an excel file using a button click. And for some reason it's not working. I've tried several things. Any ideas why they are not working?
Method 1 I have tried. This opens the file manager but does not open the proper file. It is definitely using the proper path to the file and the file does exist
private string fileCopy;
public RepairResultsControl()
{
InitializeComponent();
}
public void Show(PSRepair.AnalysisResults analysis, string pathNameCopy)
{
fileCopy = pathNameCopy;
Show();
}
private void btnGoToFile_Click(object sender, EventArgs e)
{
Process.Start("explorer.exe", "/select,"+ fileCopy);
}
Method 2. This just didn't open anything not sure why
System.Diagnostics.Process.Start(#"C:\Users\username\Documents\newTest.xlsx");
Normally, Process.Start(#"C:\Users\username\Documents\newTest.xlsx"); would open your document in Excel.
However, you say in a comment that you are doing this from an Excel add-in which runs in the background. The solution needs to take this into account (the code sample assumes that you have a VSTO add-in, otherwise you need to adjust accordingly):
// make the running Excel instance visible
Globals.ThisAddIn.Application.Visible = true;
// open the workbook using Excel interop
Globals.ThisAddIn.Application.Workbooks.Open(fileName);
Try running as an admin
Check for exceptions, also the start method should return a bool, check to make sure it is true.
Make SURE your xlsx files are associated with Excel(easy check for this is at a command prompt, type in your filename and hit enter... if excel opens you are good)
Check your system error logs.

How can I make a windows media player control's URL truly null?

I am trying to modify my track's metadata, but I can't because the file I try to edit is constantly in use. I believe this is because my axwindowsmediaplayer control is still reading from the file. I want it to stop reading from the file so I can edit it, but it seems I can't make its URL property equivalent to nothing- it wants to keep the same URL if I tell it to set the URL to null or " ". If I give it an invalid URL though, it errors. How can I make it so its URL is actually null or better yet, make it so it stops reading from my file altogether?
private void editTrackMetadataToolStripMenuItem_Click(object sender, EventArgs e)
{
Form metaform = new MetaData();
metaform.Show();
Properties.Settings.Default.StopMedia = true;
axWindowsMediaPlayer1.URL = null;//ahahahahahahaha
}
According to the documentation, it is possible to release the current resource with the close method.
Try
axWindowsMediaPlayer1.currentPlaylist.clear();
For folks who are still looking for answers:
close method does not work, it stops the player but you can still click the
play button to play the old one.
axWindowsMediaPlayer1.currentPlaylist.clear(); works as a charm.

Using Process.Start to open a text file in PFE

I wonder if you can help me with this one. I have looked on Google but found nothing.
I have a program, that once it is finished comparing 2 files together, it writes out all the differences to a text file. I have 2 radio buttons, one to open in Notepad and the other to open in PFE (Programmers File Editor).
My PFE.exe is in "C:\Program Files (x86)\PFE\PFE.exe" and Notepad is where it normally is by default.
My code is:
using System.Diagnostics;
...
if (radioButton1.Checked)
{
Process.Start("notepad.exe", File1.Text);
}
if (radioButton2.Checked)
{
Process.Start("PFE32.exe", File1.Text);
}
Now, just "Process.Start("notepad.exe", File1.Text);" works fine, without the if statements.
So, therefore, my question is - Can you help me figure out why PFE won't open with the text file?
Thank you guys!
PFE32.exe is not found, because it is not in any of the directories declared in the PATH environment variable.
You need to either add C:\Program Files (x86)\PFE to the path variable or call PFE32.exe with the full path.
The second parameter is arguments to the command, notepad doesn't need an argument name, just the file name to work.
Perhaps PFE takes a named argument like: pfe32.exe -path:C:\myfile.txt

Categories

Resources