I'm trying to get the metadata from an absolute URL to a song, such as http://www.<url>.com/<file>.mp3
How do I go about doing this. I'm a little new to the C# api's so I'm a little lost in terms of what classes to use.
I found this block of code from searching around:
StorageFile newFile = //file
var prop =await newFile.Properties.GetMusicPropertiesAsync();
string album = prop.Album;
and I was wondering what goes in the //file field? What class is of type StorageFile that will take in a URI?
Thank you.
First, you can download the mp3 file to local using this:
WebClient Client = new WebClient ();
Client.DownloadFile("http://myserver.com/indie/band1.mp3", "band1.mp3");
Then, use TagLibSharp https://github.com/mono/taglib-sharp
//Local reference to the file
TagLib.File file = TagLib.File.Create("band1.mp3");
//Get the file metadata
Console.WriteLine("Tags on disk: " + file.TagTypesOnDisk);
Console.WriteLine("Tags in object: " + file.TagTypes);
Write ("Grouping", file.Tag.Grouping);
Write ("Title", file.Tag.Title);
Write ("Album Artists", file.Tag.AlbumArtists);
Write ("Performers", file.Tag.Performers);
Write ("Composers", file.Tag.Composers);
Write ("Conductor", file.Tag.Conductor);
Write ("Album", file.Tag.Album);
Write ("Genres", file.Tag.Genres);
Write ("BPM", file.Tag.BeatsPerMinute);
Write ("Year", file.Tag.Year);
Write ("Track", file.Tag.Track);
Write ("TrackCount", file.Tag.TrackCount);
Write ("Disc", file.Tag.Disc);
Write ("DiscCount", file.Tag.DiscCount);
Related
I'm using the Movie Maker Library Timeline SDK Control 6.0 dll
And to add a photo you need a STRING of a file name. So far everything is fine
But I want to insert a function that gets an IMAGE object
But the library does not have a function that cables an IMAGE object
What I need is to get the file name out of the IMAGE object
That is: string fileName = image
Image img = default;
using (WebClient client = new WebClient())
{
string url = textBox1.Text;
Stream stream = client.OpenRead(url);
img = Image.FromStream(stream);
axTimelineControl1.AddImageClip(trackIndex: 1, fileName :img.ToString(),
clipStartTime: axTimelineControl1.GetMediaDuration(img.ToString()), clipStopTime: 4);
}
You've got a small bit of an "XY problem" here--you're asking the wrong question. Your axTimelineControl1 expects an image's file name. This implies that it also expects there to be an image saved to disk with that file name.
But all you have is a remote image, behind some URL. client.OpenRead(url) downloads the image into a Stream, but you can't do anything with that directly.
So, you don't want to take that image, and put it into a WinForms Image object. Instead, you want to save that image to disk with a file name, and then give that file name to your axTimelineControl1.
You have a few options for doing that:
1) You could take the Stream you got from client.OpenRead(), turn it into a FileStream and save it to disk.
2) You could use the WebClient to download the image directly to disk, and then give the image's file name to the axTimelineControl1.
Let's do 2) instead. It'll save a few steps.
First, create the file.
string fileName = System.IO.Path.GetTempFileName();
System.IO.File.Create(fileName).Close();
We're creating a "Temp" file here--these are meant to be treated as disposable. Note that Windows doesn't clean them up for you, so once you're done with it, your program should delete it. System.IO.File.Create() gives us a FileStream object, but we don't need it, so we Close() it right away, so that the WebClient will be able to write to our file.
Next, we download our image, and tell WebClient to save it to our newly-created Temp file:
// Defining my own URL here. Feel free to substitute your own.
string url = "https://derpicdn.net/img/view/2018/5/18/1735426.jpeg";
using (var client = new WebClient())
{
client.DownloadFile(url, fileName);
}
Now we have an image on disk, and we can tell the Movie Maker SDK Control where to find it:
float duration = axTimelineControl1.GetMediaDuration(fileName);
axTimelineControl1.AddImageClip(
trackIndex: 1,
fileName: fileName,
clipStartTime: duration,
clipStopTime: 4);
And that should do it.
The entire code listing:
string fileName = System.IO.Path.GetTempFileName();
System.IO.File.Create(fileName).Close();
// Defining my own URL here. Feel free to substitute your own.
string url = "https://derpicdn.net/img/view/2018/5/18/1735426.jpeg";
using (var client = new WebClient())
{
client.DownloadFile(url, fileName);
}
float duration = axTimelineControl1.GetMediaDuration(fileName);
axTimelineControl1.AddImageClip(
trackIndex: 1,
fileName: fileName,
clipStartTime: duration,
clipStopTime: 4);
Don't forget to clean up your temp file!
I am facing issue while downloading/exporting XML file from C# model to local machine of browser(I have front end for it).
However I am able to download/export the file from C# model to XML and save it on directory on server.
I am using below code for it :
var gradeExportDto = Mapper.Map<GradeExportDto>(responseGradeDto);
System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(gradeExportDto.GetType());
var path = _configuration.GetValue<string>(AppConstants.IMPORT_EXPORT_LOCAL_URL) + "\\"+ responseGradeDto.Code+"_"+DateTime.UtcNow.ToString("yyyy-MM-dd") + ".xml";
System.IO.FileStream file = System.IO.File.Create(path);
writer.Serialize(file, gradeExportDto);
file.Close();
Angular Code :
onExport(selectedData: any): void{
this.apiService.post(environment.api_url_master, 'ImportExport/ExportGrade/', selectedData).subscribe(result => {
this.translateService.get('GradeExportSuccess').subscribe(value => this.toastr.success(value));
}, err => {
this.toastr.error(err.message);
});
}
I need help in getting this file downloaded to local system on which browser is running.
Please let me know if more information is required from my side.
NOTE : I am not trying to download existing file. I have model in C# which I need to convert in XML and then download it to my local. However I am able to convert it to XML but not able to download on local.
You cannot save anything directly to a client machine. All you can do is provide the file as a response to a request, which will then generally prompt a download dialog on the client, allowing them to choose to save it somewhere on their local machine.
What #croxy linked you to is how to return such a response. If the issue is that the answer is using an existing file, you can disregard that part. The idea is that you're returning a byte[] or stream, regardless of where that's actually coming from. If you're creating the XML in memory, then you can simply do something like:
return File(memoryStream.ToArray(), "application/xml", "file.xml");
Instead of serializing your data into a file, serialize it into a stream eg. MemoryStream and return a File() from your action:
public IActionResult GetXml()
{
var gradeExportDto = Mapper.Map<GradeExportDto>(responseGradeDto);
var writer = new System.Xml.Serialization.XmlSerializer(gradeExportDto.GetType());
var stream = new MemoryStream();
writer.Serialize(stream, gradeExportDto);
var fileName = responseGradeDto.Code + "_" + DateTime.UtcNow.ToString("yyyy-MM-dd") + ".xml";
return File(stream.ToArray(), "application/xml", fileName);
}
I'm having trouble retrieving videos that I have recorded from my app on my iPhone.
The purpose of this is to upload this recorded video to Amazon Web Service's cloud (store it in a bucket).
However I seem to only be have directory access capabilities instead of the actual files. I don't know if this is a permissions issue or if there's a specific class that allows me to retrieve recorded videos.
This snippet of code saves the video:
var options = new PHAssetResourceCreationOptions {};
var changeRequest = PHAssetCreationRequest.CreationRequestForAsset ();
changeRequest.AddResource (PHAssetResourceType.Video, outputFileUrl, options);
The path from the outputFileUrl, which saves to the iPhone's temp folder, is how I was going about trying to retrieve the file to upload but to no success.
Can someone help me with this?
I have an toggle Record Event that gets the file like this:
// Start recording to a temporary file.
MovieFileOutput.StartRecordingToOutputFile (new NSUrl(GetTmpFilePath ("mov"), false), this);
This is the definition for GetTmpFilePath():
static string GetTmpFilePath (string extension)
{
// Start recording to a temporary file.
string outputFileName = NSProcessInfo.ProcessInfo.GloballyUniqueString;
string tmpDir = Path.GetTempPath();
string outputFilePath = Path.Combine (tmpDir, outputFileName);
return Path.ChangeExtension (outputFilePath, extension);
}
outputFileUrl is a NSUrl and is the result of this, it is a parameter to the method that uses this in the "AddResource" above.
I have embed sample.txt(it contains just one line "aaaa" ) file into project's resources like in this answer.
When I'm trying to read it like this:
string s = File.ReadAllText(global::ConsoleApplication.Properties.Resources.sample);
I'm getting System.IO.FileNotFoundException' exception.
Additional information: Could not find file 'd:\Work\Projects\MyTests\ConsoleApplication\ConsoleApplication\bin\Debug\aaaa'.
So seemingly it's trying to take file name from my resource file instead of reading this file. Why is this happening? And how can I make it read sample.txt
Trying solution of #Ryios and getting Argument null exception
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication.Resources.sample.txt"))
{
TextReader tr = new StreamReader(stream);
string fileContents = tr.ReadToEnd();
}
The file is located in d:\Work\Projects\MyTests\ConsoleApplication\ConsoleApplication\Resources\sample.txt
p.s. Solved. I had to set Build Action - embed resource in sample.txt properties
You can't read Resource Files with File.ReadAllText.
Instead you need to open a Resource Stream with Assembly.GetManifestResourceStream.
You don't pass it a path either, you pass it a namespace. The namespace of the file will be the Assemblies Default Namespace + The folder heieracy in the project the file is in + the name of the file.
Imagine this structure
Project (xyz.project)
Folder1
Folder2
SomeFile.Txt
So the namespace for the file will be:
xyz.project.Folder1.Folder2.SomeFile.Txt
Then you would read it like so
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("xyz.project.Folder1.Folder2.SomeFile.Txt"))
{
TextReader tr = new StreamReader(stream);
string fileContents = tr.ReadToEnd();
}
Hello the proposed solution doesn't work
This return null:
Assembly.GetExecutingAssembly().GetManifestResourceStream("xyz.project.Folder1.Folder2.SomeFile.Txt")
Another way is to use a MemoryStream from the Ressource Data:
byte[] aa = Properties.Resources.YOURRESSOURCENAME;
MemoryStream MS =new MemoryStream(aa);
StreamReader sr = new StreamReader(MS);
Not ideal but it works
Given a stream object which contains an xlsx file, I want to save it as a temporary file and delete it when not using the file anymore.
I thought of creating a class that implementing IDisposable and using it with the using code block in order to delete the temp file at the end.
Any idea of how to save the stream to a temp file and delete it on the end of use?
Thanks
You could use the TempFileCollection class:
using (var tempFiles = new TempFileCollection())
{
string file = tempFiles.AddExtension("xlsx");
// do something with the file here
}
What's nice about this is that even if an exception is thrown the temporary file is guaranteed to be removed thanks to the using block. By default this will generate the file into the temporary folder configured on the system but you could also specify a custom folder when invoking the TempFileCollection constructor.
You can get a temporary file name with Path.GetTempFileName(), create a FileStream to write to it and use Stream.CopyTo to copy all data from your input stream into the text file:
var stream = /* your stream */
var fileName = Path.GetTempFileName();
try
{
using (FileStream fs = File.OpenWrite(fileName))
{
stream.CopyTo(fs);
}
// Do whatever you want with the file here
}
finally
{
File.Delete(fileName);
}
Another approach here would be:
string fileName = "file.xslx";
int bufferSize = 4096;
var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose)
// now use that fileStream to save the xslx stream
This way the file will get removed after closing.
Edit:
If you don't need the stream to live too long (eg: only a single write operation or a single loop to write...), you can, as suggested, wrap this stream into a using block. With that you won't have to dispose it manually.
Code would be like:
string fileName = "file.xslx";
int bufferSize = 4096;
using(var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose))
{
// now use that fileStream to save the xslx stream
}
// Get a random temporary file name w/ path:
string tempFile = Path.GetTempFileName();
// Open a FileStream to write to the file:
using (Stream fileStream = File.OpenWrite(tempFile)) { ... }
// Delete the file when you're done:
File.Delete(tempFile);
EDIT:
Sorry, maybe it's just me, but I could have sworn that when you initially posted the question you didn't have all that detail about a class implementing IDisposable, etc... anyways, I'm not really sure what you're asking in your (edited?) question. But this question: Any idea of how to save the stream to temp file and delete it on the end of use? is pretty straight-forward. Any number of google results will come back for ".NET C# Stream to File" or such.
I just suggest for creating file use Path.GetTempFileName(). but others depends on your usage senario, for example if you want to create it in your temp creator class and use it just there, it's good to use using keyword.