UWP - Reading the windows protocol value in the Package.appxmanifest programmatically - c#

Im trying to access my appManifest file programmatically in my windows universal platform app.
I need to read the value under windows protocol extension.
any one has done anything similar?

The 'Package.appxmanifest' file is in the Application install directory. You could use the Storage relevant APIs to get it. For example:
var file = await Package.Current.InstalledLocation.GetFileAsync("AppxManifest.XML");
Please note that the files in Application install directory are read-only. You could only read it, not writable.
After get the 'AppxManifest.XML' file, you could use System.Xml relevant APIs to get the specific node.
var file = await Package.Current.InstalledLocation.GetFileAsync("AppxManifest.XML");
using (Stream stream = await file.OpenStreamForReadAsync())
{
var doc = XDocument.Load(stream);
//...
}

Related

How to upload to OneDrive using Microsoft Graph Api in c#

I have been trying to upload to a OneDrive account and I am hopelessly stuck not being able to upload neither less or greater than 4MB files. I have no issues accessing the drive at all, since I have working functions that create a folder, rename files/folders, and a delete files/folders.
https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=csharp
This documentation on Microsoft Graph API is very friendly to HTTP code, and I believe I am able to fairly "translate" the documentation to C#, but still fail to grab a file and upload to OneDrive. Some places online seem to be using byte arrays? Which I am completely unfamiliar with since my primary language is C++ and we just use ifstream/ofstream. Anyways, here is the portion of code in specific (I hope this is enough):
var item = await _client.Users[userID].Drive.Items[FolderID]//"01YZM7SMVOQ7YVNBXPZFFKNQAU5OB3XA3K"].Content
.ItemWithPath("LessThan4MB.txt")//"D:\\LessThan4MB.txt")
.CreateUploadSession()
.Request()
.PostAsync();
Console.WriteLine("done printing");
As it stands, it uploads a temporary file that has a tilde "~" in the OneDrive (like as if I was only able to open but not import any data from the file onto it). If I swap the name of the file so it includes the file location it throws an error:
Message: Found a function 'microsoft.graph.createUploadSession' on an open property. Functions on open properties are not supported.
Try this approach with memory stream and PutAsync<DriveItem> request:
string path = "D:\\LessThan4MB.txt";
byte[] data = System.IO.File.ReadAllBytes(path);
using (Stream stream = new MemoryStream(data))
{
var item = await _client.Me.Drive.Items[FolderID]
.ItemWithPath("LessThan4MB.txt")
.Content
.Request()
.PutAsync<DriveItem>(stream);
}
I am assuming you have already granted Microsoft Graph Files.ReadWrite.All permission. Check your API permission. I tested this code snippet with pretty old Microsoft.Graph library version 1.21.0. Hopefully it will work for you too.

UWP: How do I read lyrics from a local music file?

The lyrics are nested in the music file, not downloaded from the internet. the MusicProperties does not have such attribute.
I have tried using Id3 package to read it and that requires path to the file. However, in UWP there seems no way to access a file using path like C:/Users/Seaky/Desktop/Music/SomeMusic.mp3 (at least not working for me as I get permission denied even with broadFileSystemAccess.).
What else can I try?
I have found a way to do that as Mp3 accepts a Stream object in its constructor. Therefore, I am able to do this:
public async Task<string> GetLyrics()
{
var file = await StorageFile.GetFileFromPathAsync(Path);
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
using (var mp3 = new Mp3(stream.AsStream()))
{
var lyrics = mp3.GetTag(Id3TagFamily.Version2X).Lyrics;
return lyrics.Count > 0 ? lyrics[0].Lyrics : "";
}
}
}
Accessing files from a UWP application outside a select number folders requires additional permissions.
As you've pointed out, you've added the broadFileSystemAccess capability to your app manifest, which should allow access to any file that the end-user has access to.
The broadFileSystemAccess capability still requires the end-user to authorize the application. The end-user is usually prompted to do this if broadFileSystemAccess capability is specified and the permission has not yet been granted, however, in some cases, this is broken. So you could check that the application has the required permissions, via the "Advanced Settings" link to your app under the Windows "Apps & settings" settings page.
If you're hardcoding the path, you could try letting the end-user pick the file using FileOpenPicker instead, to see if that makes a difference.
There is further information on file access permissions here.

WP8.1: Exporting data to "reachable" .txt file

I am creating an app that is tracking GPS data (latitude, longitude, altitude). So far I've managed to create a listbox that gets an extra line everytime another set of coordinates is made.
I tried writing it to file with this function.
private async Task WriteToFile()
{
string ResultString = string.Join("\n", locationData.ToArray());
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(ResultString);
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var dataFolder = await local.CreateFolderAsync("DataFolder", CreationCollisionOption.OpenIfExists);
var file = await dataFolder.CreateFileAsync("DataFile.txt", CreationCollisionOption.ReplaceExisting);
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
I can read this file, but I can't view this "DataFile.txt" anywhere in Files app.
I tried using WP Power Tools, but it doesn't work with 8.1, I am unable to update Visual Studio 2013 in order to get ISExplorer.exe working and
IsoStoreSpy keeps crashing everytime I try to connect my Lumia 620.
But all of this looks too complitated to me. Is there any other way of getting this .txt file without messing with IsolatedStorage? I feel like I'm missing out on something so simple here, I just can't believe that such basic thing as writing output to .txt, that can be later used by PC, couldn't be available.
You're storing the file in your app's local storage (Windows.Storage.ApplicationData.Current.LocalFolder), which is the same as Isolated Storage.
The Files app can see only public locations not app-specific locations.
There are several ways your app can share this file more globally:
Use the share contract to let the user share the file to wherever they'd like (OneNote, Email, etc.). See Sharing and exchanging data
Let the user choose where to save the file with a FileSavePicker. See How to save files through file pickers
Save the file on the SD card. See Access the SD card in Windows Phone apps.
Save the file to the user's OneDrive. See Guidelines for accessing OneDrive from an app
Save to a RoamingFolder so the file can be read by the same app on a Windows PC, which can then export using similar methods (especially a file picker) but on the desktop device. See Quickstart: Roaming app data

A default path when downloading PDF file in computer/mobile phone

I created a PDF webapp where users are able to generate various type of PDF on both the computer and mobile phone. However, i run my program on a localhost and this is how i save my PDF based on my computer's file directory
var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
However, when i publish my webapp onto azure, i wasn't able to download from both my computer and mobile phone. Therefore i believe that it could be due to my default file directory.
Hence i would like to ask how to do a default file directory for all computer and mobile phone?
Or could it be i left out something that is necessary when the webapp is published online
Thanks.
PS : I hardcoded a default file path in order for me to test my application on a localhost to ensure a perfect working condition. Therefore i'm finding a way to find a default common file directory for all mobile/computer users when they attempt to download the PDF instead of my usual hard-coded file path
UPDATE
I tried using the method Server.MapPath but receive some error.
var doc1 = new Document();
var filename = Server.MapPath("~/pdf") + "MyTestPDF" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf";
// var output = new FileStream(Path.Combine("C:\\Users\\apr13mpsip\\Downloads", filename), FileMode.Create);
//iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
using (var output = File.Create(filename))
{
iTextSharp.text.pdf.PdfWriter.GetInstance(doc1, output);
}
doc1.Open();
This is the error i received
ObjectDisposedException was unhandled by user code
Cannot access a closed file.
When you write a Web Application you shall never use hard coded paths, and the last place where you should save files is C:\Users !! It does not matter whether this is Azure or not. It is general rule for any kind of web applications!
In your case I suggest that you create a folder within your application named pdf or something like that and save files there with the following code:
var fileName = Server.MapPath("~/pdf") + filename;
using (var output = File.Create(fileName) )
{
// do what you want with that stream
// usually generate the file and send to the end user
}
However there is even more efficient way. Use the Response.OutputStream and write the resulted PDF directly to the response. Will save you a lot of space on the local server, and the logic to delete unused generated files.

'System.UnauthorizedAccessException' on reading file no extension

I am trying to read the chrome bookmark file within a windows 8 app. Problem is I am getting the 'System.UnauthorizedAccessException' exception. So basically you have to register a file type association in the app manifest but the file has no extension.
File: C:\Users\<User>\AppData\Local\Google\Chrome\User Data\Default\Bookmarks
Is this even possible in windows 8 apps?
UPDATE
Here is my file access code:
public async Task<string> ReadFile(string filename)
{
if (await FileExists(filename))
{
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(filename);
var stream = await file.OpenReadAsync();
var reader = new StreamReader(stream.AsStream());
return await reader.ReadToEndAsync();
}
else return string.Empty;
}
Windows 8 app cannot access any random file system location. It can only access
Application Folder (which is specific to your app)
Common Folders like My Pictures, My Video and similar
See this article for complete details
A workaround is to use the file picker. This allows the end user to manually select files on the filesystem. Once you have the FileStorage object from the file picker, you can then open and read the file.
Optionally, you can then save the StorageFile for later use, meaning that your app can access the file later, without the end user having to select the file again.
More info on MSDN:
File Open Picker
How to track recently used files and folders

Categories