How can I play a SWF file placed into Resources folder - c#

I need to make a Windows application in which, at loading time, I need to play a Flash (.swf) file in WebBrowser. But I can play the Flash file directly from hard disk to WebBrowser control. Here I need to play the .swf file in the Resources folder and load it in WebBrowser control. Please help.
Thanks in advance.

System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = thisExe.GetManifestResourceStream("Namespace.Filename");
byte[] data = Properties.Resources.Filename;
file.Read(data, 0, data.Length);

Add the flash(.swf ) file as embedded resource.
use this method it works as u expect.
private void Form1_Shown(object sender, EventArgs e)
{
Stream sr = Assembly.GetExecutingAssembly().GetManifestResourceStream("namespace.file.swf");
if (sr == null) return;
var reader = new BufferedStream(sr);
string tempfile = Path.GetTempFileName() + ".swf";
var data = new byte[reader.Length];
reader.Read(data, 0, (int)reader.Length);
File.WriteAllBytes(tempfile, data);
webBrowser1.Url = new Uri(tempfile);
}
Hope it helps.

Related

How can I make the data image link in ASP.NET temporary

We have an old ASP.NET application. We have an image element on one of the pages. For the security purpose we would like to stream the image instead of a direct reference. However, after the data link is generated from the stream, it appears to be permanent. Even after the application is closed, the data link is still alive.
Is there a way to make this link invalid when out of session, to somehow invalidate it, by maybe emptying a stream?
Please let me know
Thank you in advance
MemoryStream ms = new MemoryStream();
string physicalPath = "some path of an image";
using (FileStream fs = new FileStream(physicalPath, FileMode.Open, FileAccess.Read))
{
fs.CopyTo(ms);
}
img.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray(), 0, ms.ToArray().Length);
Found a solution
Changes the above code to
Session["ImageStream"] = true;
img.ImageUrl = "MyImage.aspx";
Where the code for the MyImage.aspx is
protected override void Page_Load(object sender, EventArgs e)
{
if (Session["ImageStream"] != null && (bool)Session["ImageStream"])
{
string somePath = "Some path";
byte[] imageBytes = File.ReadAllBytes(somePath);
Response.BinaryWrite(imageBytes);
}
}
You may consider placing a javascript code that change the element "src" attribute when the session is expired.

c#, mp3 and file path

Hello I am new at c# and I am doing a small game that I need to play mp3 files.
I've been searching about this and using wmp to do it, like this:
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
myplayer.URL = #"c:\somefolder\project\music.mp3";
myplayer.controls.play();
I am able to play the file successfully with the full path of the mp3 file. The problem is that I can't find a way to use the file directly from the project folder, I mean, if I copy the project to another computer the path of the mp3 file will be invalid and no sound will be played. I feel that I am at a dead end now, so if someone can help me I would appreciate it! Thanks in advance
Another simple option to use would be:
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
string mp3FileName = "music.mp3";
myplayer.URL = AppDomain.CurrentDomain.BaseDirectory + mp3FileName;
myplayer.controls.play();
This will play the MP3 from the directory that your executable is located in. It is also important to note that no reflection is needed, which can add unnecessary performance cost.
As a follow up to the comment about embedding the MP3 as a resource, the following code can be implemented once it has been added:
Assembly assembly = Assembly.GetExecutingAssembly();
string tmpMP3 = AppDomain.CurrentDomain.BaseDirectory + "temp.mp3";
using (Stream stream = assembly.GetManifestResourceStream("YourAssemblyName.music.mp3"))
using (Stream tmp = new FileStream(tmpMP3, FileMode.Create))
{
byte[] buffer = new byte[32 * 1024];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
// Creates a temporary MP3 file in the executable directory
tmp.Write(buffer, 0, read);
}
}
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
myplayer.URL = tmpMP3;
myplayer.controls.play();
// Checks the state of the player, and sends the temp file path for deletion
myplayer.PlayStateChange += (NewState) =>
{
Myplayer_PlayStateChange(NewState, tmpMP3);
};
private static void Myplayer_PlayStateChange(int NewState, string tmpMP3)
{
if (NewState == (int)WMPPlayState.wmppsMediaEnded)
{
// Deletes the temp MP3 file
File.Delete(tmpMP3);
}
}
Add the MP3 file to your project. Also flag it to always copy to output folder. Here you have a tutorial of how to do it (How to include other files to the output directory in C# upon build?). Then you can reference this way:
You have to use:
using System.Windows.Forms;
And then you can use like this:
WindowsMediaPlayer myplayer = new WindowsMediaPlayer();
myplayer.URL = Application.StartupPath + "\music.mp3";
myplayer.controls.play();
This should work for any machine, provided your mp3 & exe are in same folder.
string mp3Path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + mp3filename

AXWindowsMediaPlayer not finding embedded resource MP3

I have a embedded resource file (MP3 to be exact) that plays a short boop. I wanted it for easy transport of the file since I have a lot more of them that I'm looking to add in.
When I try to play it, WMP just says it cannot find the file.
I'm using axWindowsMediaPlayer1.URL = #"ultraelecguitar.Properties.Resources.pitchedbeep"; to access it. It is added in the resource manager, and marked as a embedded resource. When I run my program with the file in the directory, it works just fine. When I don't, it doesn't work at all.
If you save resource as temporary file then you could provide it's path as url.
static void Main(string[] args)
{
var wmp = new WMPLib.WindowsMediaPlayer();
wmp.URL = CreateTempFileFromResource("ConsoleApplication1.mp3.somefile.mp3");
Console.ReadKey();
}
private static string CreateTempFileFromResource(string resourceName)
{
var tempFilePath = Path.GetTempFileName() + Path.GetExtension(resourceName);
using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (var tempFileStream = new FileStream(tempFilePath, FileMode.Create))
{
resourceStream.CopyTo(tempFileStream);
}
return tempFilePath;
}

process cannot access the image file because it is being used by another process

i downloaded images from my deployed website and save it into my WPF app folder , basically i am running 2 platforms , a website and WPF . What i am trying to do is users uploaded their images using the web , so on the WPF side , i download the image from the web and display on my WPF app but i got this error :
The process cannot access the file
'C:\Users\apr13mpsipa\Desktop\OneOrganizer\OneOrganizer\bin\Debug\TaskImage\Fill
in the blanks.jpg' because it is being used by another process.
This is the code :
protected void DownloadData(string strFileUrlToDownload, string taskName)
{
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(myDataBuffer.Length);
storeStream.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Flush();
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
using (FileStream file = new FileStream(currentpath, FileMode.Create, System.IO.FileAccess.ReadWrite)) // ERROR HERE
{
byte[] bytes = new byte[storeStream.Length];
storeStream.Read(bytes, 0, (int)storeStream.Length);
file.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Close();
}
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
}
I got the error when i try to display a image on a first button click , then i display the image again on the other button . basically this happens when i try to display the image 2 times.
---EDIT ------
Updated as of baldrick's comment :
DownloadData(fileUploadDirectory + daoTask.GetImage(aid, actTask.taskID).Substring(1), daoTask.GetTaskName(aid, actTask.taskID));
Image imgActivityTask = new Image();
imgActivityTask.Height = 90;
imgActivityTask.Width = 90;
imgActivityTask.Margin = new Thickness(10);
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = new Uri(currentpath, UriKind.Absolute);
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.EndInit();
imgActivityTask.Source = img;
Its still giving me the same error on the using line.
In you WPF code, you might need to specify the IgnoreImageCache setting:
yourImage.CacheOption = BitmapCacheOption.OnLoad;
yourImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache
This might force it to load, and not lock the file.
The answer here deals with the same problem.
I am guessing you are leaving the file stream open.
Not sure why you are creating a memory stream (by the way, don't forget to close memory stream), and a file stream when you already have the bytes? Why not directly write to the file using File.WriteAllBytes?
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
File.WriteAllBytes(currentPath, myDataBuffer);
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
Not sure why you are creating a memory stream (by the way, don't forget to close memory stream), and a file stream when you already have the bytes? Why not directly write to the file using File.WriteAllBytes?
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
currentpath = System.IO.Directory.GetCurrentDirectory() + #"\TaskImage\" + taskName + ".jpg"; //folder to contain files.
File.WriteAllBytes(currentPath, myDataBuffer);
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
Thanks

Reloading and refreshing flash files inside a windows form

Using DOTNET 3.5 . I have a app which shows load a flash movie in form, using this code
axShockwaveFlash1 = new AxShockwaveFlashObjects.AxShockwaveFlash()
axShockwaveFlash1.LoadMovie(0, Form1.currentGame);
The problem is that whenever I make a changes in the flash hosted in our application and try to refresh the to see the changes, the new changes is 'messed' up. to be more specific , it seems that the background and some controls of the previous flash still remain, 'spoiling' the new flash that is loaded. why?
Using the following methods before loading the second flash video makes no difference
axShockwaveFlash1.Refresh();
axShockwaveFlash1.Stop();
I tried other methods, it doesn't work for me. Here is what I did to achieve the desired result.
private void btnReload_Click(object sender, EventArgs e)
{
byte[] fileContent = File.ReadAllBytes(Application.StartupPath + #"\yourflashfile.swf");
if (fileContent != null && fileContent.Length > 0)
{
using (MemoryStream stm = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(stm))
{
/* Write length of stream for AxHost.State */
writer.Write(8 + fileContent.Length);
/* Write Flash magic 'fUfU' */
writer.Write(0x55665566);
/* Length of swf file */
writer.Write(fileContent.Length);
writer.Write(fileContent);
stm.Seek(0, SeekOrigin.Begin);
/* 1 == IPeristStreamInit */
//Same as LoadMovie()
this.axShockwaveFlash1.OcxState = new AxHost.State(stm, 1, false, null);
}
}
fileContent = null;
GC.Collect();
}
}
I copied the core code somewhere in SO but I don't remember the source.
Have you tried loading an "empty" flash video before loading your new video?
e.g.
axShockwaveFlash1.LoadMovie(0,"");
I'm sure that I encountered a similar problem and resolved it this way.
Try this.
Make a blank swf. "Blank.swf" load it first and then re-load your game.
axShockwaveFlash1.LoadMovie(0,"Blank.swf");
axShockwaveFlash1.Play();
axShockwaveFlash1.LoadMovie(0, Form1.currentGame);
axShockwaveFlash1.Play();
Ensure you give the correct path for the Blank.swf.

Categories