.net Maui android how to retrieve file from external fileserver - c#

I am making an app that allows you to open and edit a pdf file on tablets. Because i usually work with .NET, i decided to write it in .NET MAUI. That way i also have access to windows tablets.
It uses Itext as its main library to read and edit the pdf's.
I have an external shared fileserver that anyone can access when they are coneected to the WIFI.
I'd like to access that fileserver when i connect from my android tablet using Itext pdfreader.
How do I achieve this correctly?
Am i missing a library or a package which would allow to me to access that file?
Are there options i haven't discovered yet?
This works on windows tablets:
string dest "\\\\Path\\to\\File\\";
string file = "\\\\Path\\to\\File\\file.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfReader(file), new PdfWriter(dest));
I have tried :
string file = Environment.GetFolderPath(Environment.SpecialFolder.Windows)+ "\\Path\to\File\file.pdf";
string file = "\\\\Path\\to\\File\\file.pdf";
All of them result in file not found
Among the getfolderpath options ive tried a dozen, none of them seem to work.
thank you for your time

So i ended up solving this by transforming the document into a base64 string and sending it through an api that i had.
i used the classic httprequest aproach that you can look up and copy anywhere.

Related

Downloaded files using WebClient.DownloadFile() do not work

So I've been trying to download a file from MediaFire using WebClient.DownloadFile(), but all files I download do not work properly. I've tried to download PDF files and PNG files, none of them open correctly in their respective software. I'm using this for a WinForms desktop application. I've already searched for multiple solutions but none of them apply to my situation.
This is the code I've used:
private void downloadFile(string url, string filename)
{
var client = new WebClient();
client.DownloadFile(url, filename);
}
I'm a begginer so any help is appreciated!
I found the solution myself with some help from Jimi.
I needed to find the link the page was using for the download process, not the link to the page itself. I did this by accessing the code of the page using the inspect tool and finding the direct link to the file, then using my previous method it worked just fine.

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.

Xamarin Android 16 Jelly Bean / 4.1 create folder and file

I know c#; have developed for windows mobile; I now have an android project with constraints that I cannot change; the most important being cannot run above API 16 due to the devices the app will be running on. These devices are already purchased. I’m aware of the age of these devices, and how old 4.1 is; hands tied.
I’ve started a new Xamarin (not forms) project for android only; compile using 8.1 Oreo; Min version 4.1, target version 8.1. I’m aware this is not ideal however doing so I’ve managed to get lots of other needed features working including camera and barcode scanner. Changing compile version down to 4.1 causes numerous errors which won’t compile.
I’m testing the device using usb-debugging on the actual device and even though it’s 4.1, the code runs and features work – camera, scanner etc.
I’m stuck trying to create a folder and then write/read a file in that folder. I’d like this folder to be accessible via windows explorer when plugged into computer.
I’ve got code like this to write a file:
string FileContents = "Text file contents";
Java.IO.File SaveFolder = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory("Documents") + Java.IO.File.Separator + "FolderName");
Boolean Success = false;
if (!SaveFolder.Exists())
{
Success = SaveFolder.Mkdirs();
}
string FName = "test.txt";
string FTogether = System.IO.Path.Combine(SaveFolder.Path, FName);
Java.IO.FileWriter fw = new Java.IO.FileWriter(FTogether);
fw.Write(FileContents);
fw.Close();
SaveFolder.Dispose();
And code like this to read the file:
Java.IO.File SaveFolder = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory("Documents") + Java.IO.File.Separator + "FolderName");
string FName = "test.txt";
string FTogether = System.IO.Path.Combine(SaveFolder.Path, FName);
StreamReader sr = new StreamReader(FTogether);
string FileContents = sr.ReadToEnd();
Debugging reveals SaveFolder’s AbsolutePath to be /storage/sdcard0/Documents/FolderName
I think this is part of the android’s internal storage which the app has access to but nothing else.
How do I get a folder which is accessible from outside the app ?
Environment.DirectoryDocuments
cannot be used because it’s null at runtime on API 16.
The path you have is actually publicly accessible so it's not specific to your application. When you connect your Android device to the computer, you should be able to go to the root folder of the device and see the Documents folder.
Don't let the /storage/sdcard0/ part in the beginning of the path confuse you. For historical reasons, Android simulates an sdcard even if there isn't one physically on the device. In reality, /storage/sdcard0/ is just a symlink to /data/media/0.
For a really good overview of Android storage, I'd recommend you read this very thorough Reddit post: Let's clear up the confusion regarding storage in Android once and for all, including adoptable storage in Marshmallow.
What you can also do is download a file explorer app (in case your phone doesn't already have one) and go to the Documents folder. You should see FolderName there.
Edit: Since you're running on such an old version of you might also suffer from the bug in the MTP protocol, which causes newly created files and folders to be invisibile when attaching the device to a computer via USB.
The fix is to call MediaScannerConnection.scanFile for each new file/folder you've created, as explained here.

Read an Excel (xlsx) file on OneDrive using C# & ASP.NET MVC

I have a OneDrive shared link for an excel file with some data. And I need to read this excel file through my C# ASP.NET MVC web application without downloading it to local PC. But I'm new to this 'OneDrive API'. So I have a serious challenge with this. I'm familiar with local file read as in,
EX:
var package = new ExcelPackage(new System.IO.FileInfo(PATH));
I'd really appreciate if anyone can guide me or provide a sample code to do this. I just need to access the ExcelPackage of the .xlsx file. Thank you in advance.
PS : I have tried some options like 'WebRequest', 'Webclient', etc. :(
You could try something like HttpClient.GetStreamAsync to open a download stream for the remote file and then pass the returned Stream to the ExcelPackage constructor (documentation states it has a constructor that accepts an instance of a Stream).
Hope it helps!

PDFsharp generates blank page in Azure, but works locally

This works in an ASP.NET MVC application when run locally, but not when deployed on Azure:
Document doc = new Document();
Section section = doc.AddSection();
section.AddParagraph("Some text to go into a PDF");
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always);
pdfRenderer.Document = doc;
pdfRenderer.RenderDocument();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
pdfRenderer.PdfDocument.Save(stream, false);
Byte[] documentBytes = stream.ToArray();
return File(documentBytes, "application/pdf");
Locally, I get a nice PDF. On Azure, I get a blank PDF. I'm not seeing any exceptions thrown or other error messages. I found some SO answers stating that the GDI version of PDFsharp doesn't work on Azure, so I'm using the WPF version instead - same result.
I found this SO question, but I'm not clear how to apply it to an MVC app: Why is MigraDoc generating a blank pdf in my asp.net application?
Sorry if this is an obvious question, I'm just stuck!
It's likely a font problem if a complete PDF arrives at the client (I asked for conformation in a comment but got no answer yet).
PDFsharp must have access to the TTF files to extract information. Are the fonts you use in the %windir%\fonts folder and does your process have privileges to read them?
Azure is a candidate for IFontResolver because many fonts are missing and privileges are usually not granted.
With IFontResolver you give PDFsharp direct access to the TTF files (as byte[]).
You can use my class EZFontResolver for that purpose:
http://developer.th-soft.com/developer/2015/12/11/ezfontresolver-a-generic-font-resolver-for-pdfsharp-and-migradoc/
I also have a sample that shows how to implement your own IFontResolver:
http://developer.th-soft.com/developer/2015/09/21/using-private-fonts-with-pdfsharp-1-50-beta-2-or-migradoc/

Categories