Copy or open external file in windows RT app - c#

I would like to show a pdf from a website in my windows rt app (for Desktops with windows 8). How can I handle this?
If I add the file manually to the asset I can display it. But how can I do this with files where are not located on my asset Folder?
Can I copy the file to the StorageFolder?
Or can I directly open the file from the website?
Please give me some hints how I can solve this.
THX

To open files from you application you use Launcher in Windows 8 Applications. Refer the MSDN LINK: http://msdn.microsoft.com/en-in/library/windows/apps/hh701465.aspx and http://www.codeguru.com/win_mobile/win_store_apps/launching-files-with-associated-programs-in-windows-8.x-and-vb.htm

Hi I want to open it in my app and I not want to use the launcher.
I copy the file with HttpWebRequest to LocalFolder and process the pdf. I've solved it this way:
StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filepath);
//TODO Systemuser
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
var response = await request.GetResponseAsync();
List<Byte> allBytes = new List<byte>();
using (Stream imageStream = response.GetResponseStream()) {
byte[] buffer = new byte[4000];
int bytesRead = 0;
while ((bytesRead = await imageStream.ReadAsync(buffer, 0, 4000)) > 0) {
allBytes.AddRange(buffer.Take(bytesRead));
}
}
file = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(file, allBytes.ToArray());
await RenderPDFPage(fileName);

Related

how to get Bytes of a file for sending in UWP?

I'm a newbie in UWP and i want to open a file of any type and transmit the bytes of it to the reciever. forexample for a jpg file i wrote this code:
// Create FileOpenPicker instance
FileOpenPicker fileOpenPicker = new FileOpenPicker();
// Set SuggestedStartLocation
fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
// Set ViewMode
fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
fileOpenPicker.FileTypeFilter.Clear();
fileOpenPicker.FileTypeFilter.Add(".jpg");
// Open FileOpenPicker
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
byte[] bytesRead = File.ReadAllBytes(file.Path);
string Paths =
#"C:\\Users\zahraesm\Pictures\sample_reconstructed.jpg";
File.WriteAllBytes(Paths, bytesRead);
the two last lines are for writing the bytes into a file supposing in the receiver. However i keep getting the following exception:
System.InvalidOperationException: 'Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run.'
Try this Code.
try {
FileOpenPicker openPicker = new FileOpenPicker {
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
FileTypeFilter = { ".jpg", ".jpeg", ".png" }
};
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null) {
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read)) {
var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
var LoadReader = await reader.LoadAsync((uint)fileStream.Size);
byte[] pixels = new byte[fileStream.Size];
reader.ReadBytes(pixels);
}
}
} catch (Exception ex) {
}
consider wrapping last operation in Task.Run()
await Task.Run(()=>{
byte[] bytesRead = File.ReadAllBytes(file.Path);
string Paths =
#"C:\\Users\zahraesm\Pictures\sample_reconstructed.jpg";
File.WriteAllBytes(Paths, bytesRead);
});
You should directly read the bytes from the StorageFile returned from your FilePicker, lest you end up with File permission errors in the future.
StorageFile file = await fileOpenPicker.PickSingleFileAsync();
var buffer = await FileIO.ReadBufferAsync(file);
byte[] bytes = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(buffer);
You should also use await FileIO.WriteBytesAsync(targetFile, myBytes) to write.
Unless you have broadFileSystemAccess in your package Manifest, you should generally avoid using the System.IO API unless you know your application explicitly has permission to access files in that area (i.e., your application's local storage), and instead use Windows.Storage API's
Check MSDN for File Access Permissions for UWP apps for more information on file permissions.
And if you do use System.IO, always perform the work on the background thread via await Task.Run(() => { ... }

FTP Client ul/dl in Universal Windows app

I'm struggling with uploading and downloading files to a FTP server in UWP/Windows Store apps.
The FtpWebRequest Class is missing so you have to use your own Ftp Client. I haven't found any working open-source libraries for this yet. I tried Windows 8.1 Sockets: Ftp Client Sample with Sockets in C#/Xaml; The directory listing works fine but the up/download breaks after a few bytes. Maybe a buffer issue? This is the upload stream, the download function is on the msdn site.
using (var stream = await ftpClient.OpenWriteAsync(newFilePath))
{
var bytes = System.Text.Encoding.UTF8.GetBytes(filecontent);
await stream.WriteAsync(bytes.AsBuffer());
await stream.FlushAsync();
}
or
using (var stream = await OpenWriteAsync(destination))
{
// A more efficient way, maybe a DataReader can be used here
using (var readStream = await file.OpenReadAsync())
{
var buffer = new byte[512].AsBuffer();
var resultingBuffer = new byte[0];
while (true)
{
IBuffer readBuffer = await readStream.ReadAsync(buffer, 512, InputStreamOptions.Partial);
if (readBuffer.Length == 0) break;
resultingBuffer = resultingBuffer.Concat(readBuffer.ToArray()).ToArray();
}
await stream.WriteAsync(resultingBuffer.AsBuffer());
await stream.FlushAsync();
}
}
I read that the FTP upload is not supported by the BackgroundTransfer class. Has someone found a solution for loading files to a password-protected FTP server in UWP apps?
Thanks for your help!

"File-name" has been damaged : Windows Phone 8.1

I am launching document from isolated storage, when I debug on next code, previous stream gets closed and getting this exception.
"File-Name" has been damaged and can't be opened.
See my code below:
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (stream = storageFile.OpenFile("Document.docx", FileMode.Create))
{
await stream.WriteAsync(buffer, 0, buffer.Length);
}
}
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile pdffile = await local.GetFileAsync("Document.docx");
await Windows.System.Launcher.LaunchFileAsync(pdffile);
1) Make Sure If you are Downloading file from the URI than you should use WebClient instead of HttpWebRequest
2) Make sure you paas the correct URI

Issues with webscraping in C#: Downloading and parsing zipped text files

I am writing an webscraper, to do the download content from a website.
Traversing to the website/URL, triggers the creation of a temporary URL. This new URL has a zipped text file. This zipped file has to be downloaded and parsed.
I have written a scraper in C# using WebClient and its function DownloadFileAsync(). The zipped file is read from the designated location on a trapped DownloadFileCompleted event.
My issue is The Windows Open/Save dialog are triggered. This requires user input and the automation is disrupted.
Can you suggest a way to bypass the issue ? I am cool with rewriting the code using any alternate libraries. :)
Thanks for reading
You can use 'HttpWebRequest' to perform the request and save the streamed bytes to disk.
var request = WebRequest.Create(#"your url here");
request.Method=WebRequestMethods.Http.Get;
var response = request.GetResponse();
using (var writeStream = new FileStream(#"path", FileMode.Create))
{
using (var readStream = response.GetResponseStream())
{
var buffer = new byte[1024];
var readCount = readStream.Read(buffer,0,buffer.Length);
while (readCount > 0)
{
writeStream.Write(buffer,0,buffer.Length);
readCount= readStream.Read(buffer,0,buffer.Length);
}
}
}

System.Unauthorizedaccesexception while reading and writing an xml using Windows 8 xaml C#

I am working on windows 8 xaml C# apps, I am trying to read a song xml and append new node to it. The code is:
StorageFolder sf;
sf = KnownFolders.MusicLibrary;
StorageFile file = await sf.GetFileAsync(strSongName);
var item = await file.OpenAsync(FileAccessMode.Read);
IRandomAccessStream raStream;
IOutputStream outputStream;
DataWriter writer;
var lc = ApplicationData.Current.LocalFolder;
var infolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(infolder.Path);
StorageFile file1 = await folder.GetFileAsync("songxml.xml");
var filetest = await file1.OpenAsync(FileAccessMode.Read);
Stream inStream = filetest.AsStreamForRead();
XDocument xdoc = XDocument.Load(inStream);
string content = xdoc.ToString();
raStream = await file1.OpenAsync(FileAccessMode.ReadWriteUnsafe);
outputStream = raStream.GetOutputStreamAt(0);
writer = new DataWriter(outputStream);
StringBuilder outputText = new StringBuilder();
outputText.Append(content.ToString());
I get a System.Unauthorizedaccessexception while running this code
My psychic debugging powers tell me you need to mention in your capabilities that you'll be accessing the Music known folder, and that you haven't done that yet.
Am I right?
I have...well actually had the same problem. Given the date of your last comment, I guess you've figured it out by now. Nevertheless, maybe there will be others that visit this thread, so...
I guess you should make sure that you've added the extensions you expect to Declarations->Supported Declarations->File Type Associations.
Maybe this limitation is not there, when using the Music Library, but for the Documents Library (make case), this is exactly the case.
Edit: Make sure you backup the contents of the LocalState folder, because every change to the application manifest results in deleting your contents.
Happy coding

Categories