Basically I am trying to get the details of a music file inside an android device (Ex. The music's title, artist, etc) and store them to a list<>. (SongData contains the list, and it contains a list of Song object.)
public void PopulateSongList(Context context) {
SongData songData = new SongData();
Android.Net.Uri musicUri = Android.Provider.MediaStore.Audio.Media.ExternalContentUri;
//Used to query the media files.
ICursor musicCursor = context.ContentResolver.Query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.MoveToFirst())
{
int songID = 0;
//get columns.
int songTitleColumn = musicCursor.GetColumnIndex("title");
int songArtistColumn = musicCursor.GetColumnIndex("artist");
//add songs to list
do
{
String songTitle = musicCursor.GetString(songTitleColumn);
//Tried, but file name does not contain file extension.
if (songTitle.ToLower().Contains(".mp4") || songTitle.ToLower().Contains(".m4a"))
{
String songArtist = musicCursor.GetString(songArtistColumn);
songData.AddNewSong(new Song(++songID, songTitle, songArtist, null));
}
}
while (musicCursor.MoveToNext());
}
}
The code works well but however in the do..while loop, songTitle also contains other files that are not music files as well.
I tried checking for file extensions but it does not work, and after using the debugger again, the file name given does not contain the file extension.
So how do I make sure that it only grabs details from a music file, and not other kind of files?
(Also, I want to grab the name of the artist of a music file, but apparently int songArtistColumn = musicCursor.GetColumnIndex("artist"); does not seem to work.)
Finally, how do I get the image of a music file? (The song image).
You can try to use musicCursor.GetColumnNames() to see what the file is allowing you to work with.
Here's an image of the possible results you can get if you execute it.
musicCursor.GetColumnNames() will return the results in a string[] so you can use List<string> songInfo = new List<string>(string[]);
A problem you might get is a NullException, this happens when the data you're trying to work with have a value of null. You'll get this value directly from the file if the Artist or other values are unknown.
I don't know where the Image file is stored, but if it's stored with the music file it will most likely be stored in a byte[]. So you'll need to convert the byte[] to an image.
Related
I am trying to empty and array of strings every-time a user clicks on load profiles so that the array doesn't get over populated with the same profiles over and over again every time they click load.
This is my array:
string[] files;
This is how i get the profiles but i need to empty it whenever getProfiles is called so it doesn't over populate with duplicate profiles
private void GetProfiles()
{
//Check if directory with saved profiles exists
if (Directory.Exists(filePath))
{
//Clear files array
//Get all of the file paths of each file in this directory
files = Directory.GetFiles(filePath);
//profileTileTemplate.SetActive(true);
//Go through each file and read the data and create a profile for each json file
for(int i = 1; i <= files.Length -1; i++)
{
string json = File.ReadAllText(files[i]);
Profile savedProfile = JsonUtility.FromJson<Profile>(json);
Instantiate(profileTileTemplate,LoadProfileTransform);
profileTileTemplate.SetActive(true);
profileTileTemplate.GetComponentInChildren<Text>().text = savedProfile.playerName;
Debug.Log(savedProfile.playerName);
}
}
}
how do i clear this array?
I have tried setting it to null but it doesn't work.
Question is not clear, but if you want to empty the array and stay with the same length then you can write this wherever you want to.
files = new string[files.Length];
As said I don't think this is related to the array at all .. GetFiles everytime returns a new array there are no duplicates.
However, you Instantiate a bunch of objects into the scene and never destroy them!
You could do this first
foreach(Transform child in LoadProfileTransform)
{
Destroy (child.gameObject);
}
and then you could simply do
foreach(var path in files)
{
var json = File.ReadAllText(path);
var savedProfile = JsonUtility.FromJson<Profile>(json);
var obj = Instantiate(profileTileTemplate,LoadProfileTransform);
obj.SetActive(true);
obj.GetComponentInChildren<Text>().text = savedProfile.playerName;
Debug.Log(savedProfile.playerName);
}
since you want to apply the text etc to the newly instantiated objects, not the original prefab.
I'll explain the problem right away, but first of all...is this achievable?
I have a Document Type in Umbraco where I store data from a Form. I can store everything except the file.
...
content.SetValue("notes", item.Notes);
content.SetValue("curriculum", item.Curriculum); /*this is the file*/
...
I'm adding items like this where SetValue comes from the following namespace namespace Umbraco.Core.Models and this is the function signature void SetValue(string propertyTypeAlias, object value)
And the return error is the following
"String or binary data would be truncated.
↵The statement has been terminated."
Did I missunderstood something? Shouldn't I be sending the base64? I'm adding the image to a media file where it creates a sub-folder with a sequential number. If I try to add an existing folder it appends the file just fine but if I point to a new media sub-folder it also returns an error. Any ideas on how should I approach this?
Thanks in advance
Edit 1: After Cryothic answer I've updated my code with the following
byte[] tempByte = Convert.FromBase64String(item.Curriculum);
var mediaFile = _mediaService.CreateMedia(item.cvExtension, -1, Constants.Conventions.MediaTypes.File);
Stream fileStream = new MemoryStream(tempByte);
var fileName = Path.GetFileNameWithoutExtension(item.cvExtension);
mediaFile.SetValue("umbracoFile", fileName, fileStream);
_mediaService.Save(mediaFile);
and the error happens at mediaFile.SetValue(...).
If I upload a file from umbraco it goes to "http://localhost:3295/media/1679/test.txt" and the next one would go to "http://localhost:3295/media/1680/test.txt". Where do I tell on my request that it has to add to the /media folder and increment? Do I only point to the media folder and umbaco handles the incrementation part?
If I change on SetValue to the following mediaFile.SetValue("curriculum", fileName, fileStream); the request succeeds but the file is not added to the content itself and the file is added to "http://localhost:3295/umbraco/media" instead of "http://localhost:3295/media".
If I try the following - content.SetValue("curriculum", item.cvExtension); - the file is added to the content but with the path "http://localhost:3295/umbraco/test.txt".
I'm not understanding very well how umbraco inserts files into the media folder (outside umbraco) and how you add the media service path to the content service.
Do you need to save base64?
I have done something like that, but using the MediaService.
My project had the option to upload multiple images on mulitple wizard-steps, and I needed to save them all at once. So I looped through the uploaded files (HttpFileCollection) per step. acceptedFiletypes is a string-list with the mimetypes I'd allow.
for (int i = 0; i < files.Count; i++) {
byte[] fileData = null;
UploadedFile uf = null;
try {
if (acceptedFiletypes.Contains(files[i].ContentType)) {
using (var binaryReader = new BinaryReader(files[i].InputStream)) {
fileData = binaryReader.ReadBytes(files[i].ContentLength);
}
if (fileData.Length > 0) {
uf = new UploadedFile {
FileName = files[i].FileName,
FileType = fileType,
FileData = fileData
};
}
}
}
catch { }
if (uf != null) {
projectData.UploadedFiles.Add(uf);
}
}
After the last step, I would loop throug my projectData.UploadedFiles and do the following.
var service = Umbraco.Core.ApplicationContext.Current.Services.MediaService;
var mediaTypeAlias = "Image";
var mediaItem = service.CreateMedia(fileName, parentFolderID, mediaTypeAlias);
Stream fileStream = new MemoryStream(file.FileData);
mediaItem.SetValue("umbracoFile", fileName, fileStream);
service.Save(mediaItem);
I also had a check which would see if the uploaded filename was ending on ".pdf". In that case I'd change the mediaTypeAlias to "File".
I hope this helps.
Working on a project that does (or will eventually do) the following:
Access all images in a folder (for test phase using a folder in AppData called 'Test Images')
Place them in a new folder, where the image name is used to place it in or create a sub-folder using an algorithm
Save images in a 'List' so that when they have been saved, they can be displayed in a picturebox on the application - where they can be cycled through using prev/next buttons
The first two steps work fine, and I have checked that the images (only using two image files for the test phase) have been placed in subfolders.
I initialised an array of strings using the Directory.GetAllFiles() function in order to do this, meaning this array contains the paths of all the files that are being copied and manipulated. As a part of this process, I added each file path to the List<Bitmap> so they were able to be displayed in the picturebox.
However, whenever I try to run the function to display the image in the picturebox, the whole application crashes. No exception thrown or anything, just the whole thing stops working. I have no idea what is going on.
I've tried this using picbox.Image = to the element on the List<Bitmap> or using picbox.ImageLocation = to it's file path, but neither has been successful.
The code that should make this happen is shown below:
public void saveLatestImages()
{
//specific path for My Pictures only
string testImagesPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images";
//if there is a Pictures folder
if (Directory.Exists(testImagesPath))
{
//get number of files in folder
int fileCount = Directory.GetFiles(testImagesPath).Count();
//more than one file in folder
if (fileCount > 0)
{
//create data structures to store file info
//filePaths holds path of each file represented as a string
string[] filePaths = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Test Images");
//for each file in Pictures...
for (int index = 0; index < fileCount; ++index)
{
//get name of image at current index
imageName = filePaths[index];
//separate the part relating to the patient name (everything before (DD/MM/YYYY))
string subSpecifier = imageName.Split('\\').Last();
subSpecifier = subSpecifier.Split('_')[0];
//add to root directory to form subfolder name
subDirectory = Path.Combine(rootDirectory, subSpecifier);
//subdirectory name formulated, check for pre-existing
//subfolder does not exist
if(!Directory.Exists(subDirectory))
{
//create it
Directory.CreateDirectory(subDirectory);
}
//otherwise, file will be added to existing directory
//take everything from end and folder\file division to get unique filename
string fileName = imageName.Split('\\').Last();
//add this to the existing subDirectory
fileName = Path.Combine(subDirectory, fileName);
//copy the image into the subfolder using this unique filename
File.Copy(imageName, fileName, true); //true gives instruction to overwrite any existing file with the same path
//add full filename to list of bitmap images
images.Add(new Bitmap(fileName));
//update the shortcut to the file in the image storage shortcut folder
shortcutDirectory = getShortcut(subSpecifier, fileName);
}
}
}
}
public void displayLatestImages()
{
//there are images in list
if (images.Count > 0)
{
//picbox defaults to first image
picboxImage.ImageLocation = Path.GetFileName(images.First().ToString());
}
//check for images before or after current image to enable buttons
checkFirstLast();
}
This shows everything that saves the images to their new file location, and should then allow the first image added to the List to be displayed.
Any advice on how to correct this would be greatly appreciated!
Thanks,
Mark
I am creating application. In that, I put combo box, combo box filled by application no. came from db. on the selection of combo box the grid fill that files which in another machine in drive. Like //user/public/af001/edit/test.JPEG and in grid I put the download link on particular row for download that file in my machine but issue is when I am downloading that file, I am not geting //user/public/af001/edit/test.JPEG.
if (e.Column Index == 0)
{
int row;
//Get the row index
row = e.Row Index;
string old Path = #"~\\Users\Public\AS\AFS1402190001\Edit\test.JPEG";
string new path = #"E:\example\";
string new File Name = "new file name";
File Info f1 = new File Info(old Path);
if (f1.Exists)
{
if (!Directory.Exists(new path))
{
Directory.Create Directory(new path);
}
f1.Copy To(string.Format("{0}{1}{2}", new path, new File Name, f1.Extension));
}
}
Can you tell me what is the issue?
Thanks for help.
The problem is at this line:
string.Format("{0}{1}{2}", new path, new File Name, f1.Extension);
it looks you are not building a correct file patch. try to use System.IO.Path.Combine to combine directory and fileName. something like:
System.IO.Path.Combine(dirPath, string.Format("{0}.{1}", fileName, extension));
of course, you might want to make sure the path/filename does not have invalid chars, you can use System.IO.Path.GetInvalidFileNameChars() and System.IO.Path.GetInvalidPathChars() to get those illegal chars that you need to avoid.
I am trying to get the last modified date from a file, but need its path? Could someone please show me how i can get the file path?
[HttpGet]
public string uploadfile(string token, string filenameP, DateTime modDate, HttpPostedFileBase file)
{
MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
byte[] data = target.ToArray();
//ModDate = File.GetLastWriteTimeUtc("Path");
}
You are creating a new file on the server when you upload. The last modified date will be "now" (the time the file is created). There is no way to snoop the user's machine to get this information (which is not part of the file itself). Can't be done with an HTTP form upload.
Now, some file types may contain metadata in the file which may have pertinent information. If you know the file type and it does contain such metadata then you can open the file and have a look.
You just don't. Most (if not all) browsers do not provide this information for security reasons in internet sceanrios.
You can read date by javascript (HTML5) and send it as hidden input field of form.
Something like
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push(f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() );
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
http://www.html5rocks.com/en/tutorials/file/dndfiles/