I am trying to learn to write a windows phone 8.1 app using c#.
I want the app to get location data, create a GPX file and write the data into a waypoint.
I can get the location, write the xml stuff I need and create a new file using the FileSavePicker.
The problem is the FileSavePicker will only create an empty file, but everything that is written into the ContinueFileSavePicker part will not work.
Does anyone know what I'm missing? Thanks
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
//await getLocation();
}
private async void Location_Click(object sender, RoutedEventArgs e)
{
await getLocation();
}
private void Save_Click(object sender, RoutedEventArgs e)
{
// Clear previous returned file name, if it exists, between iterations of this scenario
Status2.Text = "";
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
savePicker.PickSaveFileAndContinue();
}
//<summary>
//Handle the returned file from file picker
//This method is triggered by ContinuationManager based on ActivationKind
//</summary>
//<param name="args">File save picker continuation activation argment. It cantains the file user selected with file save picker </param>
public async void ContinueFileSavePicker(FileSavePickerContinuationEventArgs args)
{
StorageFile file = args.File;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == FileUpdateStatus.Complete)
{
Status2.Text = "File " + file.Name + " was saved.";
}
else
{
Status2.Text = "File " + file.Name + " couldn't be saved.";
}
}
else
{
Status2.Text = "Operation cancelled.";
}
}
The answer is found here
Reads:
Writing a text file These methods use to write a new text file in the
Local folder:
Create the new file using the method StorageFolder.CreateFileAsync.
Open the file using the method StorageFile.OpenAsync, Which returns a stream.
Open to DataWriter over the stream returned by openAsync.
Write the text to the stream With the DataWriter.WriteString method.
Flush and close the DataWriter StoreAsync using the method.
In my case the information I have in an array of bytes called "B". Then:
Await FileIO.WriteBytesAsync (File, B)
Related
I'm trying to save my text file in UWP, but It always saving to different file. By the way I'm using MVVM architecture.
My Code
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedFileName = "New Text Document";
savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
savePicker.FileTypeChoices.Add("Text Document", new List<string>() { ".txt" });
savePicker.DefaultFileExtension = ".txt";
StorageFile storageFile = await savePicker.PickSaveFileAsync();
if(storageFile != null)
{
CachedFileManager.DeferUpdates(storageFile);
await FileIO.WriteTextAsync(storageFile, Document.Text);
FileUpdateStatus updateStatus = await CachedFileManager.CompleteUpdatesAsync(storageFile);
Document.FileName = savePicker.SuggestedFileName;
Document.IsSaved = true;
}
My code is always saving texts on different file. I'm trying to save my text to same file.
In UWP there is a feature called FutureAccessList. It can be used to save the token of the file, opened with the FilePicker. When you now want to save it again you can retrive the StorageFile by the token and write to it.
Add a FileToken property to your Document class:
public string FileToken { get; set; }
Now when you pick your file you add the file to the FutureAccessList:
...
StorageFile storageFile = await savePicker.PickSaveFileAsync();
if (storageFile != null)
{
CachedFileManager.DeferUpdates(storageFile);
await FileIO.WriteTextAsync(storageFile, Document.Text);
FileUpdateStatus updateStatus = await CachedFileManager.CompleteUpdatesAsync(storageFile);
Document.FileName = savePicker.SuggestedFileName;
Document.IsSaved = true;
//Add the file to the FutureAccessList to get it back later
Document.FileToken = StorageApplicationPermissions.FutureAccessList.Add(storageFile);
}
To retrive the file and save it again:
public async void SaveFile()
{
//Get the file back from the FutureAccessList by its token and write to it
StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(Document.FileToken);
await FileIO.WriteTextAsync(file, Document.Text);
}
Now when you e.g. save your Document class to Json and retrive it after the app restarts you can still use the FileToken to write to the file. There is no need to let the user pick it again using the SaveFilePicker.
When the code above is to complicated or there is no need for this (I don't know what you need this for), you can put a StorageFile propertie directly to your Document class and put the file, that the SaveFilePicker returned in it. But this won't work when restarting the app. The user would always have to pick the file again.
I want to use/read attached files from an outlook email into a WinForm solution.
Ex: the email has a TXT file attached; I want to perform a Drag&Drog of the TXT file into the WinForm and read the TXT at the same time.
This is an old question, but I'll provide another answer anyhow that doesn't involve using the Outlook objects.
This URL provides working code that is about 13 years old, but still seems to work, on how to handle the "FileGroupDescriptor" and "FileContents" data that Outlook passes to the DropDrop event. Just in case that link dies, here is the relevant code, copy/pasted directly:
DragEnter event:
private void Form1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
// for this program, we allow a file to be dropped from Explorer
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{ e.Effect = DragDropEffects.Copy;}
// or this tells us if it is an Outlook attachment drop
else if (e.Data.GetDataPresent("FileGroupDescriptor"))
{ e.Effect = DragDropEffects.Copy;}
// or none of the above
else
{ e.Effect = DragDropEffects.None;}
}
DragDrop event:
private void Form1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
string [] fileNames = null;
try
{
if ( e.Data.GetDataPresent(DataFormats.FileDrop,false) == true)
{
fileNames = (string []) e.Data.GetData(DataFormats.FileDrop);
// handle each file passed as needed
foreach( string fileName in fileNames)
{
// do what you are going to do with each filename
}
}
else if (e.Data.GetDataPresent("FileGroupDescriptor"))
{
//
// the first step here is to get the filename
// of the attachment and
// build a full-path name so we can store it
// in the temporary folder
//
// set up to obtain the FileGroupDescriptor
// and extract the file name
Stream theStream = (Stream) e.Data.GetData("FileGroupDescriptor");
byte [] fileGroupDescriptor = new byte[512];
theStream.Read(fileGroupDescriptor,0,512);
// used to build the filename from the FileGroupDescriptor block
StringBuilder fileName = new StringBuilder("");
// this trick gets the filename of the passed attached file
for(int i=76; fileGroupDescriptor[i]!=0; i++)
{ fileName.Append(Convert.ToChar(fileGroupDescriptor[i]));}
theStream.Close();
string path = Path.GetTempPath();
// put the zip file into the temp directory
string theFile = path+fileName.ToString();
// create the full-path name
//
// Second step: we have the file name.
// Now we need to get the actual raw
// data for the attached file and copy it to disk so we work on it.
//
// get the actual raw file into memory
MemoryStream ms = (MemoryStream) e.Data.GetData(
"FileContents",true);
// allocate enough bytes to hold the raw data
byte [] fileBytes = new byte[ms.Length];
// set starting position at first byte and read in the raw data
ms.Position = 0;
ms.Read(fileBytes,0,(int)ms.Length);
// create a file and save the raw zip file to it
FileStream fs = new FileStream(theFile,FileMode.Create);
fs.Write(fileBytes,0,(int)fileBytes.Length);
fs.Close(); // close the file
FileInfo tempFile = new FileInfo(theFile);
// always good to make sure we actually created the file
if ( tempFile.Exists == true)
{
// for now, just delete what we created
tempFile.Delete();
}
else
{ Trace.WriteLine("File was not created!");}
}
}
catch (Exception ex)
{
Trace.WriteLine("Error in DragDrop function: " + ex.Message);
// don't use MessageBox here - Outlook or Explorer is waiting !
}
}
Note that this code doesn't Dispose of objects that it should, such as the MemoryStream and FileStream objects.
You can get the running Outlook instance by using the GetActiveObject method which allows to obtain a running instance of the specified object from the running object table (ROT). Then you can automate Outlook to get the currently selected or opened item from which an attachment might be dragged. See C# app automates Outlook (CSAutomateOutlook) for the sample code.
In my application I want to give user the option to download a PDF file. In my code, the file gets opened by browser; however, I want the file to be downloaded. Here's my code:
Controller
string name = id; //id is the name of the file
string contentType = "application/pdf";
var files = objData.GetFiles(); //list of files
string filename = (from f in files
orderby f.DateEncrypted descending
where f.FileName == name
select f.FilePath).First(); //gets the location of the file
string FullName = (from f in files
where f.FileName == name
select f.FileName).First(); //gets the new id in new location to save the file with that name
//Parameters to File are
//1. The File Path on the File Server
//2. The content type MIME type
//3. The parameter for the file save by the browser
return File(filename, contentType, FullName);
Here's how I'm using it in dropdown menu.
View:
<li><a id="copyURL" href="#Url.Action("Download", "Home", new { id = item.FileName})">Download</a></li>
By clicking on "Download", the file gets opened browser.
Set your content type to "application/octet-stream" so the PDF plugin won't try to pick it up and display it. Then the browser will handle it as a file download.
Download Files from Web:
This example shows how to download files from any website to local disk. The simply way how to download file is to use WebClient class and its method DownloadFile. This method has two parameters, first is the url of the file you want to download and the second parameter is path to local disk to which you want to save the file.
Download File Synchronously
The following code shows how to download file synchronously. This method blocks the main thread until the file is downloaded or an error occur (in this case the WebException is thrown).
[C#]:
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("pdf file address", #"c:\myfile.pdf");
Download File Asynchronously:
To download file without blocking the main thread use asynchronous method DownloadFileAÂsync. You can also set event handlers to show progress and to detect that the file is downloaded.
[C#]:
private void btnDownload_Click(object sender, EventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri("pdf file address"), #"c:\myfile.pdf");
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}
ref: http://www.csharp-examples.net/download-files/
Browser will try to show the file unless you specify not to.
Try Adding ContentDisposition before returning File.
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filename, contentType, FullName);
Hello in my app I download ".mp3" file into isolated storage and user should be able to listen this ".mp3" file but it seems i cant reach ".mp3" file in play click event
here is my code
private IsolatedStorageFile isoStore;
public mp3kuran()
{
InitializeComponent();
using ( isoStore= IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStore.DirectoryExists("/shared/transfers"))
{
isoStore.CreateDirectory("/shared/transfers");
}
}
}
string link= "https://dl.dropboxusercontent.com/u/75638865/001.mp3";
private BackgroundTransferRequest transferRequest;
here is my download button action it downloads the mp3 file
private void download_Click(object sender, RoutedEventArgs e)
{
Uri transferuri = new Uri(Uri.EscapeUriString(link), UriKind.RelativeOrAbsolute);
// Create the new transfer request, passing in the URI of the file to
// be transferred.
transferRequest = new BackgroundTransferRequest(transferuri);
// Set the transfer method. GET and POST are supported.
transferRequest.Method = "GET";
string downloadFile = link.Substring(link.LastIndexOf("/") + 1);
Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = downloadFile;
// Add the transfer request using the BackgroundTransferService. Do this in
// a try block in case an exception is thrown.
try
{
BackgroundTransferService.Add(transferRequest);
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Unable to add background transfer request. " + ex.Message);
}
catch (Exception)
{
MessageBox.Show("Unable to add background transfer request.");
}
}
here play button click event
private void play_Click(object sender, RoutedEventArgs e)
{
string fileName = transferRequest.Tag;
MessageBox.Show(fileName);
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists(fileName))
{MessageBox.Show("here");
using (var isoStream = isoStore.OpenFile(fileName, FileMode.Open, FileAccess.Read))
{
mediaSound.Stop();
mediaSound.SetSource(isoStream);
mediaSound.Position = System.TimeSpan.FromSeconds(0);
mediaSound.Volume = 20;
mediaSound.Play();
}
}
}
}
in play_clic event i try to reach mp3 from isolated storage but i couldnt solve what is wrong because when I click button ,it does nothing
Some ideas...
Are you checking the BackgroundTransferRequest has completed before allowing the play button to be clicked?
Are you sure the complete file has been successfully downloaded by checking for the presence of a physical file, the same size as the original? You can use a tool like Windows Phone Toolkit to check this.
It does the Tag property on your BackgroundTransferRequest maintain the correct value after the download is complete?
Normally you'd check the status of the BackgroundTransferRequest and copy the file out of "/shared/transfers" to your own location. You'd then play the file from that location.
I have build an app with a webbrowser in it. It's working fine but when I try to navigate to an adress like bla.pdf the webbrowser shows nothing.
I solved this problem with automatically open the Internet Explorer if the adress is linking to a pdf file.
Is there a better solution? I want to open that PDF file in my own app and I dont want to open the Internet Explorer everytime. Any suggestions?
If you've got a locally downloaded PDF that is in Isolated Storage you can launch the PDF Reader application (or any other applications registered to open PDF files) using LaunchFileAsync.
private async void LaunchFileButton_Click(object sender, RoutedEventArgs rea)
{
// Access isolated storage.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Access the PDF.
StorageFile pdfFile = await local.GetFileAsync("file1.pdf");
// Launch the bug query file.
Windows.System.Launcher.LaunchFileAsync(pdfFile);
}
(adapted from MSDN, see section on "launching a file").
If it's a remote URL then you can use LaunchUriAsync (which will use IE to download the file first).
You will need to try this on a device with the PDF Reader application installed - it won't work on the Emulator.
You should read following article if you are not familiar with Async: MSDN Asynchronous Programming with Async and Await
I couldn't test my app because my WP8 Phone is currently not available and I can't install an PDF reader on the emulator.
Call following method to start the download
WebClient pdfDownloader = null;
string LastFileName = ""; //To save the filename of the last created pdf
private void StartPDFDownload(string URL)
{
pdfDownloader = new WebClient(); //prevents that the OpenReadCompleted-Event is called multiple times
pdfDownloader.OpenReadCompleted += DownloadPDF; //Create an event handler
pdfDownloader.OpenReadAsync(new Uri(URL)); //Start to read the website
}
async void DownloadPDF(object sender, OpenReadCompletedEventArgs e)
{
byte[] buffer = new byte[e.Result.Length]; //Gets the byte length of the pdf file
await e.Result.ReadAsync(buffer, 0, buffer.Length); //Waits until the rad is completed (Async doesn't block the GUI Thread)
using (IsolatedStorageFile ISFile = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
LastFileName = "tempPDF" + DateTime.Now.Ticks + ".pdf";
using (IsolatedStorageFileStream ISFileStream = ISFile.CreateFile(LastFileName))
{
await ISFileStream.WriteAsync(buffer, 0, buffer.Length);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.HResult,
ex.Source, MessageBoxButton.OK);
//Catch errors regarding the creation of file
}
}
OpenPDFFile();
}
private async void OpenPDFFile()
{
StorageFolder ISFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
try
{
IStorageFile ISFile = await ISFolder.GetFileAsync(LastFileName);
await Windows.System.Launcher.LaunchFileAsync(ISFile);
//http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206987%28v=vs.105%29.aspx
}
catch (Exception ex)
{
//Catch unknown errors while getting the file
//or opening the app to display it
}
}
To call these methods from your WebBrowser-Control you need to catch the navigating event.
YourWebBrowserControl.Navigating += YourWebBrowserControl_Navigating;
void YourWebBrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
if(e.Uri.AbsolutPath.EndsWith("pdf"))
{
StartPDFDownload(e.Uri.ToString());
}
}
Don't forget that you'll have to delete the files created someday.
Try this to open a PDF from a WebControl:
void MyWebBrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
if (e.Uri.AbsolutPath.ToLower().EndsWith(".pdf"))
{
var success = Windows.System.Launcher.LaunchUriAsync(e.Uri);
}
}