Ejemplo n.º 1
0
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            // Open a save dialog for the user.
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("KMZ file", new List <string>()
            {
                ".kmz"
            });
            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                try
                {
                    using (Stream stream = await file.OpenStreamForWriteAsync())
                    {
                        // Write the KML document to the stream of the file.
                        await _kmlDocument.WriteToAsync(stream);
                    }
                    await new MessageDialog("Item saved.").ShowAsync();
                }
                catch
                {
                    await new MessageDialog("File not saved.").ShowAsync();
                }
            }
        }
Ejemplo n.º 2
0
        public async void ApplyTag()
        {
            Windows.Storage.StorageFolder folder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(FolderUrl);

            Windows.Storage.StorageFile file = await folder.GetFileAsync(FileName);

            Stream fileStream = await file.OpenStreamForWriteAsync();

            TagLib.File tagFile = TagLib.File.Create(new StreamFileAbstraction(FileName, fileStream, fileStream));
            tagFile.Tag.Title      = Title;
            tagFile.Tag.Performers = new string[] { Artist };
            tagFile.Tag.Album      = Album;
            if (tagFile.MimeType == "taglib/mp3")
            {
                IPicture pic = GeneratePicture();
                if (pic != null)
                {
                    tagFile.Tag.Pictures = new IPicture[] { pic };
                }
            }
            if (tagFile.MimeType == "taglib/flac")
            {
            }
            tagFile.Save();
            tagFile.Dispose();
            fileStream.Close();
        }
        public async void HttpDownloadFile(Windows.Storage.StorageFolder folder, string name)
        {
            String url = "http://music.163.com/song/media/outer/url?id=" + tb.Text;
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();

            //创建本地文件写入流
            try
            {
                Windows.Storage.StorageFile f = await folder.CreateFileAsync(name + ".mp3", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                Stream stream = await f.OpenStreamForWriteAsync();

                byte[] bArr = new byte[1024];
                int    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                stream.Close();
                responseStream.Close();
                ShowMessageBox("下载成功", "已存储" + name + ".mp3" + "至" + folder.Path);
            }
            catch (Exception e)
            {
                ShowMessageBox("拒绝访问", e.Message);
            }
        }
Ejemplo n.º 4
0
                public override async Task ResetAsync()
                {
                    windowsFile = await CreateTemporaryFile();

                    fileStream = await windowsFile.OpenStreamForWriteAsync();

                    downloader = new RestRequests.Downloader(CloudFile.Id, fileStream);
                }
Ejemplo n.º 5
0
        protected async static Task <System.IO.Stream> GetFileWriterStreamAsync(Windows.Storage.StorageFile fle)
        {
            System.IO.Stream strm = null;

            strm = await fle.OpenStreamForWriteAsync();

            return(strm);
        }
Ejemplo n.º 6
0
        protected override void PrepareWriter()
        {
            IAsyncOperation <Windows.Storage.StorageFile> task = Windows.Storage.ApplicationData.Current.LocalCacheFolder.CreateFileAsync("localStorage.log",
                                                                                                                                          Windows.Storage.CreationCollisionOption.GenerateUniqueName);

            Windows.Storage.StorageFile file = task.GetAwaiter().GetResult();
            m_stream = file.OpenStreamForWriteAsync().Result;

            QuietWriter = new log4net.Util.QuietTextWriter(new StreamWriter(m_stream, Encoding.UTF8), ErrorHandler);
            WriteHeader();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// SaveBuffer method
        /// </summary>
        /// <param name="wavFile">StorageFile where the audio buffer
        /// will be stored.
        /// </param>
        /// <param name="start">the position in the buffer of the first byte to save in a file.
        /// by default the value is 0.
        /// </param>
        /// <param name="end">the position in the buffer of the last byte to save in a file
        /// by default the value is 0, if the value is 0 the whole buffer will be stored in a a file
        /// </param>
        /// <return>true if successful.
        /// </return>
        public async System.Threading.Tasks.Task <bool> SaveBuffer(Windows.Storage.StorageFile wavFile, UInt64 start = 0, UInt64 end = 0)
        {
            bool bResult = false;

            if (wavFile != null)
            {
                try
                {
                    using (Stream stream = await wavFile.OpenStreamForWriteAsync())
                    {
                        if ((stream != null) && (STTStream != null))
                        {
                            stream.SetLength(0);
                            if ((start == 0) && (end == 0))
                            {
                                await STTStream.AsStream().CopyToAsync(stream);

                                System.Diagnostics.Debug.WriteLine("Audio Stream stored in: " + wavFile.Path);
                                bResult = true;
                            }
                            else if ((start >= 0) && (end > start))
                            {
                                var headerBuffer = STTStream.CreateWAVHeaderBuffer((uint)(end - start));
                                if (headerBuffer != null)
                                {
                                    byte[] buffer = new byte[headerBuffer.Length + (uint)(end - start)];
                                    if (buffer != null)
                                    {
                                        headerBuffer.CopyTo(buffer, headerBuffer.Length);
                                        ulong pos = STTStream.Position;
                                        STTStream.Seek(start);
                                        STTStream.ReadAsync(buffer.AsBuffer((int)headerBuffer.Length, (int)(end - start)), (uint)(end - start), Windows.Storage.Streams.InputStreamOptions.None).AsTask().Wait();
                                        STTStream.Seek(pos);
                                        MemoryStream bufferStream = new MemoryStream(buffer);
                                        await bufferStream.CopyToAsync(stream);

                                        System.Diagnostics.Debug.WriteLine("Audio Stream stored in: " + wavFile.Path);
                                        bResult = true;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Exception while saving the Audio Stream stored in: " + wavFile.Path + " Exception: " + ex.Message);
                }
            }
            return(bResult);
        }
Ejemplo n.º 8
0
        private async void SaveTexture(Texture2D tex)
        {
            Windows.Storage.Pickers.FileSavePicker picker = new Windows.Storage.Pickers.FileSavePicker
            {
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeChoices.Add("Portable Network Graphics", new[] { ".png" });
            picker.SuggestedFileName = "texture";
            Windows.Storage.StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                var stream = await file.OpenStreamForWriteAsync();

                tex.SaveAsPng(stream, tex.Width, tex.Height);
            }
        }
Ejemplo n.º 9
0
        //- Notice
        //You can't define the path "System.Threading.Tasks.*" and etc. on "using" scheme
        //for respect the portable issues!
        public static async System.Threading.Tasks.Task SavePhotoTask(byte[] image, string name)
        {
            //Debug.WriteLine("[BenchImage_DEBUG]: Salvando imagem filtrada!");

            Windows.Storage.StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

            Windows.Storage.StorageFolder dataFolder = await local.CreateFolderAsync("BenchImageOutput", Windows.Storage.CreationCollisionOption.OpenIfExists);

            Windows.Storage.StorageFile file = await dataFolder.CreateFileAsync(name, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            using (var stream = await file.OpenStreamForWriteAsync())
            {
                stream.Write(image, 0, image.Length);
            }

            //Debug.WriteLine("[BenchImage_DEBUG]: Salvou imagem filtrada!");
        }
Ejemplo n.º 10
0
        private async void WriteWebInfoToLocal <T>(ObservableCollection <T> list) where T : class, new()
        {
            Windows.Storage.StorageFile file = null;
            try
            {
                file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("webinfo", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                if (file != null)
                {
                    using (Stream stream = await file.OpenStreamForWriteAsync())
                    {
                        DataContractSerializer ser = new DataContractSerializer(typeof(ObservableCollection <T>));
                        ser.WriteObject(stream, list);
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 11
0
 public async void LoggerDaemon()
 {
     while (true)
     {
         if (file != null)
         {
             if (messages.Count > 0)
             {
                 using (Stream ws = await file.OpenStreamForWriteAsync())
                 {
                     ws.Seek(0, SeekOrigin.End);
                     while (messages.TryDequeue(out string msg))
                     {
                         byte[] bytes = ASCIIEncoding.ASCII.GetBytes(msg);
                         await ws.WriteAsync(bytes, 0, bytes.Length);
                     }
                 }
             }
         }
         await System.Threading.Tasks.Task.Delay(1000);
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Saves the provided data to the file
        /// specified
        /// </summary>
        /// <param name="fullPath"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task <bool> Save(string fullPath, byte[] data)
        {
            bool retVal = false;

            // System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " DiskCache Save DeleteFile for Path: " + fullPath);
            // await DeleteFile(fullPath);
            try
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " DiskCache Save Saving for Path: " + fullPath);
                Windows.Storage.StorageFile file = await applicationData.LocalFolder.CreateFileAsync(fullPath, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                if (file != null)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " DiskCache Save OpenStreamForWriteAsync for Path: " + fullPath);
                    using (var s = await file.OpenStreamForWriteAsync())
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " DiskCache Save WriteAsync for Path: " + fullPath);
                        await s.WriteAsync(data, 0, data.Length);
                    }

                    /*
                     * System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " DiskCache Save Saving GetBufferFromBytes for Path: " + fullPath);
                     * Windows.Storage.Streams.IBuffer buffer = GetBufferFromBytes(data);
                     * System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " DiskCache Save Saving WriteBufferAsync for Path: " + fullPath);
                     * await Windows.Storage.FileIO.WriteBufferAsync(file, buffer);
                     */
                    retVal = true;
                }
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " DiskCache Save Saving done for Path: " + fullPath);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " DiskCache Save Saving exception for Path: " + fullPath + " Exception: " + e.Message);
            }

            return(retVal);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Truncate file from isolated storage file to specific size
        /// </summary>
        /// <param name="fullPath">String representation of the path to isolated storage file</param>
        /// <param name="size">bytes of file from starting postion to be kept</param>
        public async Task <bool> Truncate(string fullPath, long size)
        {
            bool bResult = false;

            if (size <= 0)
            {
                return(bResult);
            }

            bool bRes = await FileExists(fullPath);

            if (bRes != true)
            {
                return(bResult);
            }

            try
            {
                Windows.Storage.StorageFile file = await applicationData.LocalFolder.GetFileAsync(fullPath);

                if (file != null)
                {
                    using (var stream = await file.OpenStreamForWriteAsync())
                    {
                        if (stream != null)
                        {
                            stream.SetLength(size);
                            bResult = true;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return(bResult);
        }
Ejemplo n.º 14
0
                protected override async Task StartPrivateAsync()
                {
                    switch (Status)
                    {
                    case NetworkStatus.ErrorNeedRestart:
                    case NetworkStatus.NotStarted:
                    case NetworkStatus.Paused:
                    {
                        if (Status != NetworkStatus.Paused)
                        {
                            //Status = NetworkStatus.Starting;
                            //MyLogger.Assert(downloader == null && windowsFile == null && fileStream == null);
                            windowsFile = await CreateTemporaryFile();

                            fileStream = await windowsFile.OpenStreamForWriteAsync();

                            downloader = new RestRequests.Downloader(CloudFile.Id, fileStream);
                        }
                        Status = NetworkStatus.Networking;
                        var progressChangedEventHandler = new RestRequests.ProgressChangedEventHandler((bytesProcessed, totalLength) =>
                            {
                                BytesDownloaded = bytesProcessed;
                                TotalFileLength = totalLength;
                                MyLogger.Assert(this.GetType() == typeof(Downloaders.FileDownloader));
                                OnProgressChanged(BytesDownloaded, TotalFileLength);
                            });
                        var messageAppendedEventHandler = new MessageAppendedEventHandler((msg) =>
                            {
                                OnMessageAppended("Rest: " + msg);
                            });
                        downloader.ProgressChanged += progressChangedEventHandler;
                        downloader.MessageAppended += messageAppendedEventHandler;
                        await downloader.DownloadAsync();

                        downloader.ProgressChanged -= progressChangedEventHandler;
                        downloader.MessageAppended -= messageAppendedEventHandler;
                        downloadAgain_index :;
                        switch (downloader.Status)
                        {
                        case RestRequests.Downloader.DownloadStatus.Completed :
                            {
                                fileStream.Dispose();
                                Status = NetworkStatus.Completed;
                                return;
                            }

                        case RestRequests.Downloader.DownloadStatus.ErrorNeedRestart:
                        {
                            OnMessageAppended("Error need restart");
                            Status = NetworkStatus.ErrorNeedRestart;
                            return;
                        }

                        case RestRequests.Downloader.DownloadStatus.ErrorNeedResume:
                        {
                            OnMessageAppended("Error need resume...");
                            goto downloadAgain_index;
                        }

                        case RestRequests.Downloader.DownloadStatus.Paused:
                        {
                            Status = NetworkStatus.Paused;
                            return;
                        }

                        case RestRequests.Downloader.DownloadStatus.Downloading:
                        case RestRequests.Downloader.DownloadStatus.NotStarted:
                        default: throw new Exception($"downloader.Status: {downloader.Status}");
                        }
                    }

                    case NetworkStatus.Completed:
                    case NetworkStatus.Networking:
                    //case NetworkStatus.Starting:
                    default: throw new Exception($"Status: {Status}");
                    }
                }
Ejemplo n.º 15
0
        public async Task When_DateCreated()
        {
            var folderForTestFile = Windows.Storage.ApplicationData.Current.LocalFolder;

            Assert.IsNotNull(folderForTestFile, "cannot get LocalFolder - error outside tested method");

            Windows.Storage.StorageFile testFile = null;

            DateTimeOffset dateBeforeCreating = DateTimeOffset.Now;

            try
            {
                testFile = await folderForTestFile.CreateFileAsync(_filename, Windows.Storage.CreationCollisionOption.FailIfExists);

                Assert.IsNotNull(testFile, "cannot create file - error outside tested method");
            }
            catch (Exception e)
            {
                Assert.Fail($"CreateFile exception - error outside tested method ({e})");
            }

            DateTimeOffset dateAfterCreating = DateTimeOffset.Now;



            // tests of DateCreated

            DateTimeOffset dateOnCreating = DateTimeOffset.Now;             // unneeded initialization - just to skip compiler error of using uninitialized variable

            try
            {
                dateOnCreating = testFile.DateCreated;
            }
            catch (Exception e)
            {
                Assert.Fail($"DateCreated exception - error in tested method ({e})");
            }

            // while testing date, we should remember about filesystem date resolution.
            // FAT: 2 seconds, but we don't have FAT
            // NTFS: 100 ns
            // VFAT (SD cards): can be as small as 10 ms
            // ext4 (internal Android): can be below 1 ms
            // APFS (since iOS 10.3): 1 ns
            // HFS+ (before iOS 10.3): 1 s

            // first, date should not be year 1601 or something like that...
            if (dateOnCreating < dateBeforeCreating.AddSeconds(-2))
            {
                Assert.Fail("DateCreated: too early - method doesnt work");
            }

            // second, date should not be in future
            if (dateOnCreating > dateAfterCreating.AddSeconds(2))
            {
                Assert.Fail("DateCreated: too late - method doesnt work");
            }

            // third, it should not be "datetime.now"
            var initialTimeDiff = DateTimeOffset.Now - dateOnCreating;
            int loopGuard;

            for (loopGuard = 20; loopGuard > 0; loopGuard--)             // wait for date change for max 5 seconds
            {
                await Task.Delay(250);

                dateOnCreating = testFile.DateCreated;
                if (DateTimeOffset.Now - dateOnCreating > initialTimeDiff)
                {
                    break;
                }
            }
            if (loopGuard < 1)
            {
                Assert.Fail("DateCreated: probably == DateTime.Now, - method doesnt work");
            }



            // now, test Date Modified

            DateTimeOffset dateBeforeModify = DateTimeOffset.Now;
            // modify file
            Stream fileStream = await testFile.OpenStreamForWriteAsync();

            fileStream.Seek(0, SeekOrigin.End);
            StreamWriter streamWriter = new StreamWriter(fileStream);

            streamWriter.Write(_filename);              // anything - just write String
            streamWriter.Dispose();
            fileStream.Dispose();
            DateTimeOffset dateAfterModify = DateTimeOffset.Now;

            // get DateModified
            DateTimeOffset dateModified = DateTimeOffset.Now;             // unneeded initialization - just to skip compiler error of using uninitialized variable

            try
            {
                dateModified = (await testFile.GetBasicPropertiesAsync()).DateModified;
            }
            catch (Exception e)
            {
                Assert.Fail($"DateModified exception - error in tested method ({e})");
            }

            // first, date should not be year 1601 or something like that...
            if (dateModified < dateBeforeModify.AddSeconds(-2))
            {
                Assert.Fail("DateModified: too early - method doesnt work");
            }

            // second, date should not be in future
            if (dateModified > dateAfterModify.AddSeconds(2))
            {
                Assert.Fail("DateCreated: too late - method doesnt work");
            }

            // third, it should not be "datetime.now"
            initialTimeDiff = DateTimeOffset.Now - dateModified;
            for (loopGuard = 20; loopGuard > 0; loopGuard--)             // wait for date change for max 5 seconds
            {
                await Task.Delay(250);

                var dateModifiedLoop = (await testFile.GetBasicPropertiesAsync()).DateModified;
                if (DateTimeOffset.Now - dateModifiedLoop > initialTimeDiff)
                {
                    break;
                }
            }
            if (loopGuard < 1)
            {
                Assert.Fail("DateModified: probably == DateTime.Now, - method doesnt work");
            }

            // last test
            if (dateModified < dateOnCreating)
            {
                Assert.Fail("DateModified == DateCreated, - method doesnt work");
            }
        }
Ejemplo n.º 16
0
        private async System.Threading.Tasks.Task <bool> RecordTrack(string wavFile, string deviceID, int startSector, int endSector)
        {
            try
            {
                bool result = false;
                if (string.IsNullOrEmpty(deviceID))
                {
                    LogMessage("Empty deviceID");
                    return(result);
                }

                // Stop the current stream
                mediaPlayer.Source = null;
                mediaPlayerElement.PosterSource = null;
                mediaPlayer.AutoPlay            = true;


                CDTrackStream s = await CDTrackStream.Create(deviceID, startSector, endSector);

                if (s != null)
                {
                    Windows.Storage.StorageFile file = await GetFileFromLocalPathUrl(wavFile);

                    if (file != null)
                    {
                        LogMessage("Writing into : " + file.Path);

                        Stream fs = await file.OpenStreamForWriteAsync();

                        if (fs != null)
                        {
                            const int bufferSize   = 2352 * 20 * 16;
                            const int WAVHeaderLen = 44;
                            ulong     FileSize     = s.MaxSize;
                            byte[]    array        = new byte[bufferSize];
                            ulong     currentSize  = WAVHeaderLen;
                            for (ulong i = 0; i < FileSize + bufferSize; i += currentSize)
                            {
                                if (i == WAVHeaderLen)
                                {
                                    currentSize = bufferSize;
                                }
                                var b = await s.ReadAsync(array.AsBuffer(), (uint)currentSize, InputStreamOptions.None);

                                if (b != null)
                                {
                                    fs.Write(array, 0, (int)b.Length);
                                    LogMessage("Writing : " + b.Length.ToString() + " bytes " + ((((ulong)fs.Position + 1) * 100) / FileSize).ToString() + "% copied ");
                                    if (currentSize != b.Length)
                                    {
                                        break;
                                    }
                                }
                            }
                            fs.Flush();
                            return(true);
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                LogMessage("Exception Recording Track into WAV File : " + ex.Message.ToString());
            }
            return(false);
        }
        private async void Save_Click(object sender, EventArgs e)
        {
            try
            {
#if __IOS__
                // Determine the path for the file.
                string offlineDataFolder = Path.Combine(DataManager.GetDataFolder(), "CreateAndSaveKmlFile");

                // If temporary data folder doesn't exists, create it.
                if (!Directory.Exists(offlineDataFolder))
                {
                    Directory.CreateDirectory(offlineDataFolder);
                }

                string path = Path.Combine(offlineDataFolder, "sampledata.kmz");
                using (Stream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                {
                    // Write the KML document to the stream of the file.
                    await _kmlDocument.WriteToAsync(stream);
                }
                await Application.Current.MainPage.DisplayAlert("Success", "KMZ file saved locally to ArcGISRuntimeSamples folder.", "OK");
#endif
#if __ANDROID__
                // Determine the path for the file.
                string filePath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads, "sampledata.kmz");

                // Check if permission has not been granted.
                if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
                {
                    ArcGISRuntime.Droid.MainActivity.Instance.RequestPermissions(new[] { Manifest.Permission.WriteExternalStorage }, 1);
                }
                else
                {
                    using (Stream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                    {
                        // Write the KML document to the stream of the file.
                        await _kmlDocument.WriteToAsync(stream);
                    }
                    await Application.Current.MainPage.DisplayAlert("Success", "File saved to " + filePath, "OK");
                }
#endif
#if WINDOWS_UWP
                // Open a save dialog for the user.
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                savePicker.FileTypeChoices.Add("KMZ file", new List <string>()
                {
                    ".kmz"
                });
                Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

                if (file != null)
                {
                    using (Stream stream = await file.OpenStreamForWriteAsync())
                    {
                        // Write the KML document to the stream of the file.
                        await _kmlDocument.WriteToAsync(stream);
                    }
                }
#endif
            }
            catch (Exception)
            {
                await Application.Current.MainPage.DisplayAlert("Error", "File not saved.", "OK");
            }
        }
Ejemplo n.º 18
0
        public async System.Threading.Tasks.Task SaveKML(System.Collections.Generic.List <Windows.Devices.Geolocation.BasicGeoposition> mapdata)
        {
            #region XML generating

            XmlDocument    xDoc = new XmlDocument();
            XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", "utf-8", null);

            XmlElement kml = xDoc.CreateElement("kml");
            kml.SetAttribute("xmlns", @"http://www.opengis.net/kml/2.2");
            xDoc.InsertBefore(xDec, xDoc.DocumentElement);
            xDoc.AppendChild(kml);
            XmlElement Document = xDoc.CreateElement("Document");
            kml.AppendChild(Document);

            XmlElement name         = xDoc.CreateElement("name");
            XmlText    nameTextMain = xDoc.CreateTextNode(DateTime.Today.ToString());
            Document.AppendChild(name);
            name.AppendChild(nameTextMain);

            XmlElement description = xDoc.CreateElement("description");
            XmlText    destext     = xDoc.CreateTextNode("Created by JustMeasure app.");
            Document.AppendChild(description);
            description.AppendChild(destext);

            XmlElement Style = xDoc.CreateElement("Style");
            Style.SetAttribute("id", "style1");
            Document.AppendChild(Style);

            XmlElement LineStyle = xDoc.CreateElement("LineStyle");
            Style.AppendChild(LineStyle);

            XmlElement LineStyleColor = xDoc.CreateElement("color");
            XmlText    linestylecolor = xDoc.CreateTextNode("ffffffff");
            LineStyle.AppendChild(LineStyleColor);
            LineStyleColor.AppendChild(linestylecolor);

            XmlElement LineStyleWidth = xDoc.CreateElement("width");
            XmlText    linestylewidth = xDoc.CreateTextNode("5");
            LineStyle.AppendChild(LineStyleWidth);
            LineStyleWidth.AppendChild(linestylewidth);

            XmlElement Polystyle = xDoc.CreateElement("PolyStyle");
            Style.AppendChild(Polystyle);

            XmlElement polystylecolor = xDoc.CreateElement("color");
            XmlText    polyscolor     = xDoc.CreateTextNode("330000ff");
            Polystyle.AppendChild(polystylecolor);
            polystylecolor.AppendChild(polyscolor);

            XmlElement Placemark = xDoc.CreateElement("Placemark");
            Document.AppendChild(Placemark);

            XmlElement styleUrl = xDoc.CreateElement("styleUrl");
            XmlText    styleurl = xDoc.CreateTextNode("#style1");
            Placemark.AppendChild(styleUrl);
            styleUrl.AppendChild(styleurl);

            XmlElement Polygon = xDoc.CreateElement("Polygon");
            Placemark.AppendChild(Polygon);

            XmlElement extrude     = xDoc.CreateElement("extrude");
            XmlText    extrudetext = xDoc.CreateTextNode("1");
            Polygon.AppendChild(extrude);
            extrude.AppendChild(extrudetext);

            XmlElement altitudeMode     = xDoc.CreateElement("altitudeMode");
            XmlText    relativeToGround = xDoc.CreateTextNode("relativeToGround");
            Polygon.AppendChild(altitudeMode);
            altitudeMode.AppendChild(relativeToGround);

            XmlElement outerBoundaryIs = xDoc.CreateElement("outerBoundaryIs");
            Polygon.AppendChild(outerBoundaryIs);

            XmlElement LinearRing = xDoc.CreateElement("LinearRing");
            outerBoundaryIs.AppendChild(LinearRing);

            XmlElement coordinates = xDoc.CreateElement("coordinates");
            LinearRing.AppendChild(coordinates);

            for (int i = 0; i < mapdata.Count; i++)
            {
                string  coord = mapdata[i].Longitude + "," + mapdata[i].Latitude + "\n";
                XmlText cord  = xDoc.CreateTextNode(coord);
                coordinates.AppendChild(cord);
            }
            #endregion
            Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();
            savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("KML file", new System.Collections.Generic.List <string>()
            {
                ".kml"
            });
            savePicker.SuggestedFileName = DateTime.Now.ToString();
            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                Windows.Storage.CachedFileManager.DeferUpdates(file);
                using (Stream fileStream = await file.OpenStreamForWriteAsync())
                {
                    xDoc.Save(fileStream);
                }
                Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    SuccessOrNot("SuccessFile");
                }
                else
                {
                    SuccessOrNot("FailFile");
                }
            }
        }