GetBasicPropertiesAsync() 공개 메소드

public GetBasicPropertiesAsync ( ) : IAsyncOperation
리턴 IAsyncOperation
예제 #1
0
        // Fetches all the data for the specified file
        public async static Task<FileItem> fromStorageFile(StorageFile f, CancellationToken ct)
        {
            FileItem item = new FileItem();
            item.Filename = f.DisplayName;
            
            // Block to make sure we only have one request outstanding
            await gettingFileProperties.WaitAsync();

            BasicProperties bp = null;
            try
            {
                bp = await f.GetBasicPropertiesAsync().AsTask(ct);
            }
            catch (Exception) { }
            finally
            {
                gettingFileProperties.Release();
            }

            ct.ThrowIfCancellationRequested();

            item.Size = (int)bp.Size;
            item.Key = f.FolderRelativeId;

            StorageItemThumbnail thumb = await f.GetThumbnailAsync(ThumbnailMode.SingleItem).AsTask(ct);
            ct.ThrowIfCancellationRequested();
            BitmapImage img = new BitmapImage();
            await img.SetSourceAsync(thumb).AsTask(ct);

            item.ImageData = img;
            return item;
        }
예제 #2
0
 private async void SetDetails(StorageFile file)
 {
     var data = await file.GetBasicPropertiesAsync();
     _fileName = file.Name;
     _saveTime = data.DateModified.LocalDateTime;
     TxtDate.Text = _saveTime.ToString("dd/MM/yyyy HH:mm");
     TxtSize.Text = Utilities.SizeSuffix((long) data.Size);
 }
예제 #3
0
 private static async Task MergeFileIntoNote(StorageFile file, Note note)
 {
     note.DateCreated = file.DateCreated.LocalDateTime;
     BasicProperties properties = await file.GetBasicPropertiesAsync();
     note.DateModified = properties.DateModified.LocalDateTime;
     note.Name = file.Name;
     note.Text = await FileIO.ReadTextAsync(file);
     note.MarkAsClean();
 }
예제 #4
0
        public static async Task<PhotoCapturedData> CreatePhotoCapturedDataAsync(StorageFile imageFile, string categoryName)
        {
            var photoData = new PhotoCapturedData(categoryName);

            photoData.ImageFile = imageFile;

            photoData.ImageFileSize = (await imageFile.GetBasicPropertiesAsync()).Size;

            return photoData;
        }
예제 #5
0
        protected async Task <string> fileNotFound()
        {
            Windows.Storage.StorageFile htmlErrorFile = await rootDirectory.GetFileAsync("404.html");

            var properties = await htmlErrorFile.GetBasicPropertiesAsync();

            string htmlErrorPage = "HTTP/1.0 404 Not Found\r\n" +
                                   "Content-Lenght:" + properties.Size + "\r\n" +
                                   "Content-type: text/html\r\n" +
                                   "Connection: Close\r\n\r\n";

            htmlErrorPage += await Windows.Storage.FileIO.ReadTextAsync(htmlErrorFile);

            return(htmlErrorPage);
        }
예제 #6
0
        protected async Task <string> getFileFormattedHtml(string fileRequested)
        {
            Windows.Storage.StorageFile htmlPageRequested = await rootDirectory.GetFileAsync(fileRequested);

            var properties = await htmlPageRequested.GetBasicPropertiesAsync();

            string htmlPage = "HTTP/1.0 200 OK\r\n" +
                              "Content-Lenght:" + properties.Size + "\r\n" +
                              "Content-type: text/html\r\n" +
                              "Connection: Close\r\n\r\n";

            htmlPage += await Windows.Storage.FileIO.ReadTextAsync(htmlPageRequested);

            return(htmlPage);
        }
예제 #7
0
        /// <summary>
        /// Ottiene la data di ultima modifica del file IN LOCALE
        /// </summary>
        /// <param name="filename">nome del file</param>
        /// <returns>La data di modifica</returns>
        public static async Task <DateTime> getLastUpdatedDate(string filename)
        {
            try
            {
                Windows.Storage.StorageFile tsaved = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(filename);

                Windows.Storage.FileProperties.BasicProperties prop = await tsaved.GetBasicPropertiesAsync();

                return(prop.DateModified.DateTime);
            }
            catch (Exception)
            {
                return(new DateTime());
            }
        }
예제 #8
0
        internal async Task<MediaMetadata> GetMetadata(StorageFile targetFile)
        {
            if (targetFile == null) return null;
            var fileMetaData = new MediaMetadata();
            try
            {
                fileMetaData.ReferenceUrl = targetFile.Path.StartsWith(WindowsPhoneUtils.DocumentsFolder.Path) ? targetFile.Path.Replace(WindowsPhoneUtils.DocumentsFolder.Path, String.Empty) : String.Empty;
                fileMetaData.Size = (long)(await targetFile.GetBasicPropertiesAsync()).Size;
                fileMetaData.MimeType = targetFile.ContentType;
                fileMetaData.Type = MediaType.NotSupported;
                if (targetFile.ContentType.Contains("audio/"))
                {
                    var musicProperties = await targetFile.Properties.GetMusicPropertiesAsync();
                    fileMetaData.Album = musicProperties.Album;
                    fileMetaData.Artist = musicProperties.Artist;
                    fileMetaData.Category = musicProperties.Genre.Aggregate(new StringBuilder(), (sb, a) => sb.Append(String.Join(",", a)), sb => sb.ToString());
                    fileMetaData.Duration = (long)musicProperties.Duration.TotalSeconds;
                    fileMetaData.Title = musicProperties.Title;
                    fileMetaData.Type = MediaType.Audio;
                }
                else if (targetFile.ContentType.Contains("video/"))
                {
                    var videoProperties = await targetFile.Properties.GetVideoPropertiesAsync();
                    fileMetaData.Duration = (long)videoProperties.Duration.TotalSeconds;
                    fileMetaData.Artist = videoProperties.Directors.Aggregate(new StringBuilder(), (sb, a) => sb.Append(String.Join(",", a)), sb => sb.ToString());
                    fileMetaData.Title = videoProperties.Title;
                    fileMetaData.Category = videoProperties.Keywords.Aggregate(new StringBuilder(), (sb, a) => sb.Append(String.Join(",", a)), sb => sb.ToString());
                    fileMetaData.Type = MediaType.Video;

                }
                else if (targetFile.ContentType.Contains("image/"))
                {
                    var imgProperties = await targetFile.Properties.GetImagePropertiesAsync();
                    fileMetaData.Title = imgProperties.Title;
                    fileMetaData.Category = imgProperties.Keywords.Aggregate(new StringBuilder(), (sb, a) => sb.Append(String.Join(",", a)), sb => sb.ToString());
                    fileMetaData.Type = MediaType.Photo;
                }
                return fileMetaData;
            }
            catch (Exception ex)
            {
                WindowsPhoneUtils.Log(ex.Message);
                return null;
            }
        }
예제 #9
0
        /// <summary>
        /// Restituisce true se c'è abbastanza spazio nel folder per salvare il filesize
        /// </summary>
        public static async Task<bool> isThereFreeSpace(StorageFile file, StorageFolder folder)
        {
            BasicProperties bp = await file.GetBasicPropertiesAsync();
            ulong filesize = bp.Size;


            var retrivedProperties = await folder.Properties.RetrievePropertiesAsync(new string[] { "System.FreeSpace" });
            ulong sizefree = (ulong)retrivedProperties["System.FreeSpace"];

            if(filesize<sizefree)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
예제 #10
0
        private async Task<bool> Initialize(StorageFile file)
        {
            BinaryReader reader = new BinaryReader((await file.OpenAsync(FileAccessMode.Read)).AsStreamForRead());

            int chunkID = reader.ReadInt32();
            int fileSize = reader.ReadInt32() + 8;
            int riffType = reader.ReadInt32();
            int fmtID = reader.ReadInt32();
            int fmtSize = reader.ReadInt32();
            int fmtCode = reader.ReadInt16();
            int channels = reader.ReadInt16();
            int sampleRate = reader.ReadInt32();
            int fmtAvgBPS = reader.ReadInt32();
            int fmtBlockAlign = reader.ReadInt16();
            int bitDepth = reader.ReadInt16();

            if (fmtSize == 18)
            {
                // Read any extra values
                int fmtExtraSize = reader.ReadInt16();
                reader.ReadBytes(fmtExtraSize);
            }

            int dataID = reader.ReadInt32();
            int dataSize = reader.ReadInt32();

            Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync();
            System.Diagnostics.Debug.Assert(fileSize == (int)basicProperties.Size);
            Debug.Assert(fmtSize == 16);
            Debug.Assert(channels == 1);

            while (reader.BaseStream.Position != reader.BaseStream.Length)
            {
                Samples.Add(reader.ReadInt16() / Math.Pow(2.0, 15.0));
            }

            return true;
        }
예제 #11
0
        private async Task SendFileAsync(String url, StorageFile sFile, HttpMethod httpMethod)
        {
            //Log data for upload attempt
            Windows.Storage.FileProperties.BasicProperties fileProperties = await sFile.GetBasicPropertiesAsync();
            Dictionary<string, string> properties = new Dictionary<string, string> { { "File Size", fileProperties.Size.ToString() } };
            App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload attempt", properties);
            HttpStreamContent streamContent = null;

            try
            {
                //Open file to send as stream
                Stream stream = await sFile.OpenStreamForReadAsync();
                streamContent = new HttpStreamContent(stream.AsInputStream());
                Debug.WriteLine("SendFileAsync() - sending: " + sFile.Path);
            }
            catch (FileNotFoundException ex)
            {
                Debug.WriteLine(ex.Message);

                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "OneDrive", ex.Message } };
                App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events);
            }
            catch (Exception ex)
            {
                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "OneDrive", ex.Message } };
                App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events);

                throw new Exception("SendFileAsync() - Cannot open file. Err= " + ex.Message);
            }

            if (streamContent == null)
            {
                //Throw exception if stream is not created
                Debug.WriteLine("  File Path = " + (sFile != null ? sFile.Path : "?"));
                throw new Exception("SendFileAsync() - Cannot open file.");
            }

            try
            {
                Uri resourceAddress = new Uri(url);
                //Create requst to upload file
                using (HttpRequestMessage request = new HttpRequestMessage(httpMethod, resourceAddress))
                {
                    request.Content = streamContent;

                    // Do an asynchronous POST.
                    using (HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token))
                    {
                        await DebugTextResultAsync(response);
                        if (response.StatusCode != HttpStatusCode.Created)
                        {
                            throw new Exception("SendFileAsync() - " + response.StatusCode);
                        }

                    }
                }
            }
            catch (TaskCanceledException ex)
            {
                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "OneDrive", ex.Message } };
                App.Controller.TelemetryClient.TrackEvent("CancelledFileUpload", events);

                throw new Exception("SendFileAsync() - " + ex.Message);
            }
            catch (Exception ex)
            {
                // This failure will already be logged in telemetry in the enclosing UploadPictures function. We don't want this to be recorded twice.

                throw new Exception("SendFileAsync() - Error: " + ex.Message);
            }
            finally
            {
                streamContent.Dispose();
                Debug.WriteLine("SendFileAsync() - final.");
            }

            App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload success", properties);
        }
예제 #12
0
        /// <summary>
        /// Displays an image file in the 'ScenarioOutputImage' element.
        /// </summary>
        /// <param name="imageFile">The image file to display.</param>
        async private Task DisplayImageAsync(StorageFile imageFile)
        {
            var imageProperties = await imageFile.GetBasicPropertiesAsync();
            if (imageProperties.Size > 0)
            {
                rootPage.NotifyUser("Displaying: " + imageFile.Name + ", date modified: " + imageProperties.DateModified + ", size: " + imageProperties.Size + " bytes", NotifyType.StatusMessage);
                var stream = await imageFile.OpenAsync(FileAccessMode.Read);

                // BitmapImage.SetSource needs to be called in the UI thread
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    var bitmap = new BitmapImage();
                    bitmap.SetSource(stream);
                    ScenarioOutputImage.SetValue(Image.SourceProperty, bitmap);
                });
            }
            else
            {
                rootPage.NotifyUser("Cannot display " + imageFile.Name + " because its size is 0", NotifyType.ErrorMessage);
            }
        }
예제 #13
0
        public static async Task<SettingsFlyout> CreatePropertiesFlyout(StorageFile file, StorageFolder topFolder, string fileSubPath)
        {
            if (file == null) return null;

            SettingsFlyout flyout = null;
            try
            {
                BasicProperties basicProps = null;
                try { basicProps = await file.GetBasicPropertiesAsync(); }
                catch (Exception ex) { Debug.WriteLine(ex.ToString()); }

                if (file.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
                {
                    var flyoutImg = new PropertiesFlyoutImage();
                    flyout = flyoutImg;
                    ImageProperties imageProps = await file.Properties.GetImagePropertiesAsync();
                    if (imageProps != null)
                        FillImageProperties(flyoutImg, imageProps, file, basicProps);
                }
                else if (file.ContentType.ToLower().StartsWith("audio"))
                {
                    var flyoutAud = new PropertiesFlyoutAudio();
                    flyout = flyoutAud;
                    MusicProperties musicProps = await file.Properties.GetMusicPropertiesAsync();
                    if (musicProps != null)
                        await FillAudioProperties(flyoutAud, musicProps, file);
                }
                else if (file.ContentType.ToLower().StartsWith("video"))
                {
                    var flyoutVdo = new PropertiesFlyoutVideo();
                    flyout = flyoutVdo;
                    VideoProperties videoProps = await file.Properties.GetVideoPropertiesAsync();
                    if (videoProps != null)
                        FillVideoProperties(flyoutVdo, videoProps);
                }
                else
                {
                    var flyoutGen = new PropertiesFlyoutGeneral();
                    flyout = flyoutGen;
                    await FillGeneralProperties(flyoutGen, file, basicProps);
                }

                Debug.Assert(flyout != null, "Flyout object must exist.");
                if (flyout != null)
                    await FillFileProperties((IFileProperties)flyout, file, topFolder, fileSubPath, basicProps);
            }
            catch (Exception ex) { Debug.WriteLine(ex.ToString()); }
            return flyout;
        }
예제 #14
0
 private async Task<long> GetFileSize(StorageFile file)
 {
     BasicProperties props = await file.GetBasicPropertiesAsync();
     return (long)props.Size;
 }
예제 #15
0
        private static async Task<bool> IsFileOutOfDate(StorageFile file, DateTime expirationDate)
        {
            if (file != null)
            {
                var properties = await file.GetBasicPropertiesAsync();
                return properties.DateModified < expirationDate;
            }

            return true;
        }
예제 #16
0
        /// <summary>
        /// Attempts to generate a list of tests from a file. 
        /// 
        /// NB this currently only works on .py files with Python tests
        /// </summary>
        /// <param name="file"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        internal async static Task<List<Test>> GetTestsFromFile(StorageFile file, string path)
        {
            var toreturn = new List<Test>();

            if ((await file.GetBasicPropertiesAsync()).Size > 1024 * 1024 * 1024)
            {
                throw new Exception("File too large: " + file.Path);
            }

            try {
                var reader = await file.OpenReadAsync();
                var lines = await FileIO.ReadLinesAsync(file);

                foreach (string line in lines)
                {
                    if (line.Contains("def test_") && !line.Trim().StartsWith("##"))
                    {
                        var test = new Test();
                        string prefix = "";
                        if (path != "")
                        {
                            prefix = path + "/" + file.DisplayName + "/";
                        }
                        test.NameForDisplay = prefix + line.Replace("def ", "").Replace("(self):", "").Replace("test_", "").Trim();
                        test.NameInFile = line;
                        toreturn.Add(test);
                    }
                }
            } catch
            {
                return new List<Test>(); // TODO support unicode
            }

            return toreturn;
        }
예제 #17
0
 private async Task uploadFile(StorageFile file, string peer)
 {
     if (file == null) return;
     if (shareOperation != null) shareOperation.ReportStarted();
     var fileSize = (await file.GetBasicPropertiesAsync()).Size;
     if ( fileSize> 20 * 1024 * 1024)
     {
         await DialogBoxes.AskForConfirmation("File may be too big to handle. The file size is "+(fileSize/1024/1024).ToString()+"MB. Files bigger than 20 MB may cause the application to crash. Proceed at your own risk?",
             async () =>
             {
                 byte[] fileContents = (await FileIO.ReadBufferAsync(file)).ToArray();
                 if (shareOperation != null) shareOperation.ReportDataRetrieved();
                 await Communicator.SendFile(file.Name, fileContents, peer);
             });
     }
     else
     {
         byte[] fileContents = (await FileIO.ReadBufferAsync(file)).ToArray();
         if ((bool)enableEncryption.IsChecked)
         {
             await Communicator.SendFile(file.Name, fileContents, peer);
         }
         else
         {
             await Communicator.SendFileNoCrypt(file.Name, fileContents, peer);
         }
     }
 }
        public static async Task<FileInfoDataItem> Create(StorageFile file, String uniqueId, Image image, FileInfoDataGroup group)
        {
            try
            {
                var obj = new FileInfoDataItem(file, uniqueId, image, group);
                if (file != null)
                {
                    obj.FileName = file.Name;

                    if (!string.IsNullOrEmpty(ItemsPage.Current.TopFolder.Path))
                    {
                        int topFolderLen = ItemsPage.Current.TopFolder.Path.Length;
                        int lastSepIdx = file.Path.LastIndexOf('\\');
                        Debug.Assert(lastSepIdx >= 0 && lastSepIdx < file.Path.Length && lastSepIdx >= topFolderLen);
                        if (lastSepIdx >= 0 && lastSepIdx < file.Path.Length && lastSepIdx > topFolderLen)
                            obj.SubPath += file.Path.Substring(topFolderLen + 1, lastSepIdx - topFolderLen - 1);
                    }
                    else
                    {
                        int idx = !string.IsNullOrEmpty(ItemsPage.Current.TopFolder.Name) ?
                                  file.Path.IndexOf(ItemsPage.Current.TopFolder.Name, StringComparison.OrdinalIgnoreCase) : -1;
                        if (idx >= 0)
                        {
                            int idxSubPath = idx + ItemsPage.Current.TopFolder.Name.Length + 1;
                            int idxFileName = Math.Max(file.Path.LastIndexOf("\\"), 0);
                            if (idxFileName > idxSubPath)
                                obj.SubPath += file.Path.Substring(idxSubPath, idxFileName - idxSubPath);
                        }
                        else
                        {
                            idx = file.Path.LastIndexOf("\\");
                            if (idx > 0)
                                obj.SubPath = file.Path.Substring(0, idx);
                            else
                                obj.SubPath = file.Path;
                        }
                    }

                    BasicProperties props = await file.GetBasicPropertiesAsync();
                    if (props != null)
                    {
                        obj.Size = Util.SizeToString(props.Size, "B");
                        ItemsPage.Current.IncrTotalBytes(props.Size);
                    }

                    obj.DateModified = Util.DateTime_ToString(props.DateModified, Util.EDateTimeFormat.G);
                    obj.Extension = file.FileType;
                    obj.ContentType = file.ContentType;

#if DEBUG
                    {
                        string ext = (file.FileType == String.Empty) ? "EMPTY" : file.FileType;
                        string contyp = (file.ContentType == String.Empty) ? "EMPTY" : file.ContentType;

                        if (!ItemsPage.Current._ExtContyp.ContainsKey(ext))
                        {
                            //Debug.WriteLine(ext + " - " + contyp);
                            ItemsPage.Current._ExtContyp.Add(ext, contyp);
                        }
                        //else if (file.FileType == String.Empty)
                        //    Debug.WriteLine(ext + " - " + contyp);

                        //if (!ItemsPage.Current._ContypExt.ContainsKey(contType))
                        //{
                        //    Debug.WriteLine(contType + " - " + ext);
                        //    ItemsPage.Current._ContypExt.Add(contType, ext);
                        //}
                        //else if (file.ContentType == String.Empty)
                        //    Debug.WriteLine(contType + " - " + ext);
                    }
#endif
                }
                return obj;
            }
            catch (Exception ex) { Debug.WriteLine(ex.ToString()); return null; }
        }
        private async void SetDataContext(BitmapImage image, StorageFile file)
        {
            var stream = await file.OpenAsync(FileAccessMode.Read);
            var properties = await (await file.GetBasicPropertiesAsync()).RetrievePropertiesAsync(new string[] { });

            DataContext = new FileSummary(image, file, properties, stream);

            // Show the relevant sub-headers
            if (SubHeaderBasic.Visibility != Visibility.Visible)
            {
                SubHeaderBasic.Visibility = Visibility.Visible;
                SubHeaderExif.Visibility = Visibility.Visible;
                SubHeaderFull.Visibility = Visibility.Visible;
            }
        }
예제 #20
0
        /*******************************************************************************************
        * PRIVATE METHODS
        ********************************************************************************************/
        private async Task uploadPictureToAzure(string imageName, StorageFile imageFile)
        {
            //Log data for upload attempt
            Windows.Storage.FileProperties.BasicProperties fileProperties = await imageFile.GetBasicPropertiesAsync();
            Dictionary<string, string> properties = new Dictionary<string, string> { { "File Size", fileProperties.Size.ToString() } };
            TelemetryHelper.TrackEvent("Azure picture upload attempt", properties);
            try
            {
                //Create a blank blob
                CloudBlockBlob newBlob = blobContainer.GetBlockBlobReference(imageName);

                //Add image data to blob
                await newBlob.UploadFromFileAsync(imageFile);
            }
            catch(Exception ex)
            {
                //This failure will be logged in telemetry in the enclosing UploadPictures function. We don't want this to be recorded twice.
                throw new Exception("Exception in uploading pictures to Azure: " + ex.Message);
            }
            //Log successful upload event
            TelemetryHelper.TrackEvent("Azure picture upload success", properties);
        }
예제 #21
0
 private void OpenPDFDocument(Windows.Storage.StorageFile file)
 {
     if (file != null)
     {
         IAsyncOperation <Windows.Storage.FileProperties.BasicProperties> file_property = file.GetBasicPropertiesAsync();
         Windows.Storage.FileProperties.BasicProperties properties = file_property.GetResults();
         m_SDKDocument = new FSDK_Document();
         int result = m_SDKDocument.OpenDocumentAsync(file, (int)properties.Size, null).GetResults();
         if (result != 0)
         {
             return;
         }
         m_PDFDoc.pointer = m_SDKDocument.m_hDoc.pointer;
         result           = LoadPage(m_iCurPageIndex);
         if (result != 0)
         {
             return;
         }
         m_dbScaleFator = (m_dbCommonFitWidthScale < m_dbCommonFitHeightScale) ? m_dbCommonFitWidthScale : m_dbCommonFitHeightScale;
         ShowPage();
     }
     else
     {
         //ShowErrorLog("Error: Fail to pick a valid PDF file.", ref new UICommandInvokedHandler(this, renderPage.ReturnCommandInvokedHandler));
         return;
     }
 }
예제 #22
0
        private async Task<FileInfo> ScanFile(StorageFile file, bool doSha1)
        {
            var basicProps = await file.GetBasicPropertiesAsync();

            string sha1str = null;
            if (doSha1) {
                try {
                    IBuffer buffer;
                    using (var stream = await file.OpenAsync(FileAccessMode.Read)) {
                        buffer = WindowsRuntimeBuffer.Create((int)basicProps.Size); // oh no we can't read large files
                        await stream.ReadAsync(buffer, (uint)basicProps.Size, InputStreamOptions.None);
                    }

                    var hash = Sha1.HashData(buffer);
                    var hashBytes = new byte[hash.Length];
                    hash.CopyTo(hashBytes);
                    sha1str = Convert.ToBase64String(hashBytes);
                }
                catch (UnauthorizedAccessException) { }
            }

            return new FileInfo {
                Name = file.Name,
                Path = file.Path,
                Sha1 = sha1str,
                Size = basicProps.Size,
            };
        }
예제 #23
0
 private async Task<long> GetFileSizeInBytes(StorageFile file)
 {
     var fileProperties = await file.GetBasicPropertiesAsync();
     return (long) fileProperties.Size;
 }
예제 #24
0
        public async Task Show_PickerAsync(object obj)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();
            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".mp3");
            picker.FileTypeFilter.Add(".mp4");
            picker.FileTypeFilter.Add(".webm");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
            if (file != null)
            {
                // Application now has read/write access to the picked file
                string[] namedetail = file.Name.Split('.');
                Song addsong = new Song { Name = namedetail[0], Path = file.Path };
                Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync();

                string fileSize = string.Format("{0:n0}", basicProperties.Size);
                Debug.WriteLine(fileSize);
                ListSong.Add(addsong);
                DatabaseService.Instance().DB.SongDao.Insert(addsong);
/*                DatabaseService.Instance().DB.PlaylistDao.addSong(addsong,);*/

/*                Messenger.Default.Send<MessengerBus>(new MessengerBus() { NameSong = namedetail[0], Path = file.Path });*/
            }
            /*            var file = await picker.PickMultipleFilesAsync();*/
        }
        private async void UploadSingleFile(Uri uri, StorageFile file)
        {
            if (file == null)
            {
                rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
                return;
            }

            BasicProperties properties = await file.GetBasicPropertiesAsync();
            if (properties.Size > maxUploadFileSize)
            {
                rootPage.NotifyUser(String.Format(CultureInfo.CurrentCulture, 
                    "Selected file exceeds max. upload file size ({0} MB).", maxUploadFileSize / (1024 * 1024)),
                    NotifyType.ErrorMessage);
                return;
            }

            BackgroundUploader uploader = new BackgroundUploader();
            uploader.SetRequestHeader("Filename", file.Name);

            UploadOperation upload = uploader.CreateUpload(uri, file);
            Log(String.Format(CultureInfo.CurrentCulture, "Uploading {0} to {1}, {2}", file.Name, uri.AbsoluteUri, 
                upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
예제 #26
0
 private async Task CalculateFileSize(StorageFile file)
 {
     BasicProperties p = await file.GetBasicPropertiesAsync();
     m_size = (long) p.Size;
 }
        private async void ShowProperties(StorageFile file)
        {
            Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync();
            ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync();

            StringBuilder propertiesText = new StringBuilder();
            propertiesText.AppendLine((String)_resources["fileName"]+": "+file.DisplayName);
            propertiesText.AppendLine((String)_resources["fileSize"] + ": " + basicProperties.Size + " "+ (String)_resources["fileSizeBytes"]);
            propertiesText.AppendLine((String)_resources["fileType"] + ": " + file.FileType);
            propertiesText.AppendLine((String)_resources["fileDateModified"] + ": " + basicProperties.DateModified);
            propertiesText.AppendLine((String)_resources["filePath"] + ": " + file.Path);
            propertiesText.AppendLine();
            propertiesText.AppendLine((String)_resources["fileCoordinates"]);
            propertiesText.AppendLine((String)_resources["fileLongitude"] + ": " + imageProperties.Longitude);
            propertiesText.AppendLine((String)_resources["fileLatitude"] + ": " + imageProperties.Latitude);

            properties.Details = propertiesText.ToString() ; 
        }
        private static async Task<CacheItem> GetCacheItemFromFileAsync(StorageFile file)
        {
            CacheItem result = null;

            try
            {
                var fileName = file.Name;
                var basicProperties = await file.GetBasicPropertiesAsync();
                var parts = fileName.Split('.');

                if (parts.Length == 3)
                {
                    var size = GetSizeFromString(parts[1]);

                    if (size != default(Size))
                    {
                        result = new CacheItem
                            {
                                Key = parts[0],
                                ImageSize = size,
                                Size = basicProperties.Size,
                                LastAccessTime = basicProperties.DateModified.UtcDateTime
                            };
                    }
                }
            }
            catch (SecurityException)
            {
                // Doesn't metter
            }
            catch (UnauthorizedAccessException)
            {
                // Doesn't metter
            }

            return result;
        }