I basically want to be able to implement a feature for an android app to open a text file and read the contents to a string variable. I can handle this using android and Java but with forms I don't know how to go about it. I'm guessing dependency injection but a little guidance would do.
You can write your own file picker if required and use it via dependency service.
There is a plugin which does what you are asking for - FilePicker Plugin for Xamarin and Windows.
This can let you handle file handling from your pcl project.
The code is available in GitHub if you want to slightly customize it.
Eg :
private async Task PickFilesCommandHandler()
{
var file = await CrossFilePicker.Current.PickFile();
var fileEntity = new FileEntity
{
FileName = file.FileName,
DataArray = file.DataArray
};
}
Full example in Github.
For byte array to string conversion have a look at this answer.
Or use the following method via MemoryStream :
using (var ms = new MemoryStream(bytes))
{
using (var streamReader = new StreamReader(ms))
{
var str = streamReader.ReadToEnd();
}
}
Related
I have a component library that uses JS code to generate an image as a base64 string and the image needs to be transposed to C#. The image size is larger than MaximumReceiveMessageSize.
Can I get the value of the MaximumReceiveMessageSize property in C#? I need a way to correctly split the picture into chunks, or some other way to transfer it.
My component can be used in a Wasm or Server application. I can't change the value of the MaximumReceiveMessageSize property.
Thanks
Using a stream as described in the Stream from JavaScript to .NET solved my problem.
From Microsoft docs:
In JavaScript:
function streamToDotNet() {
return new Uint8Array(10000000);
}
In C# code:
var dataReference = await JS.InvokeAsync<IJSStreamReference>("streamToDotNet");
using var dataReferenceStream = await dataReference.OpenReadStreamAsync(maxAllowedSize: 10_000_000);
var outputPath = Path.Combine(Path.GetTempPath(), "file.txt");
using var outputFileStream = File.OpenWrite(outputPath);
await dataReferenceStream.CopyToAsync(outputFileStream);
In the preceding example: JS is an injected IJSRuntime instance. The dataReferenceStream is written to disk (file.txt) at the current user's temporary folder path (GetTempPath).
I want to convert HTML content to PDF. I have tried using third party API like GemBox, GrapeCity..
these all are working in UWP but in android failing.
Please suggest any solution. I can go with paid API's also.
Thanks!
If you are looking for a one-in-all solution, you can check out the leadtools document converter nuget here: https://www.nuget.org/packages/Leadtools.Document.Sdk/ disclaimer: i am employed by the vendor of this library
LEADTOOLS supports HTML -> PDF as well as a bunch of other formats. You can see more information here: https://www.leadtools.com/sdk/document/document-converter
This library supports Xamarin on Android, UWP, and iOS and is completely offline.
Here is a snippet of code that will work for your use-case:
using (var documentConverter = new DocumentConverter())
{
var htmlString = File.ReadAllText(#"./test.htm");
using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlString)))
{
var htmlDocument = DocumentFactory.LoadFromStream(ms, new LoadDocumentOptions());
var jobData = DocumentConverterJobs.CreateJobData(htmlDocument, "output.pdf", DocumentFormat.Pdf);
var job = documentConverter.Jobs.CreateJob(jobData);
documentConverter.Jobs.RunJob(job);
}
}
I am new to Xamarin. Facing a lot of difficulties due to only a fraction of .Net assemblies are available for PCL.
I need to download a .db file by hitting a URL which is required to save in local drive. As the project is in PCL So this is not allowing me to use System.IO.File in my project, so making me unable to do the file operations available in .Net class library.
Ex: Suppose I am hitting the URL "http://123.com/register.db" and this returns register.db as response. I need to save the register.db as it is in my local storage.
My code to hit the URL is as below
public static async Task LaunchURLForSync(string targetUrl)
{
try
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(targetUrl, HttpCompletionOption.ResponseHeadersRead))
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
string fileToWriteTo = Path.GetFileName();
using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create)) // This doesn't work with PCL for ex. FIle.Open etc
{
await streamToReadFrom.CopyToAsync(streamToWriteTo);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Any help will be highly appreciated. Thank you in advance :)
PCL code only has a subset of APIs available to you. In order to get access to all of the APIs, you sometime have to write native code in each platform. I would suggest reading over Xamarin's File Storage article here.
I would also highly suggest using the PCL Storage plugin which will allow you to easily run file related methods from your Xamarin Forms project. Xamarin actually also recommends this library.
To use PCL Storage to do what you want, after installing the library in your all of your projects, you would do the following:
IFile file = await folder.CreateFileAsync("myfile.abc", CreationCollisionOption.ReplaceExisting);
byte[] buffer = new byte[100];
using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite)) {
stream.Write(buffer, 0, 100);
}
I'm using the AWS SDK package from Nuget to download files from S3. This involves creating a GetObject request. Amazon has an example of how to do this in their documentation, although I'm actually using the async version of the method.
My code to download a file looks something like this:
using (var client = new AmazonS3Client(accessKey, secretAccessKey, RegionEndpoint.USEast1))
{
var request = new GetObjectRequest
{
BucketName = "my-bucket",
Key = "file.exe"
};
using (var response = await client.GetObjectAsync(request))
{
response.WriteResponseStreamToFile(#"C:\Downloads\file.exe");
}
}
This works; it downloads the file successfully. However, it seems like a little bit of a black box, in that I never really know how long it's going to take to download the file. What I'm hoping to do is get some sort of Progress event so that I can display a nice WPF ProgressBar and watch the download progress. This means I would need to know the size of the file and the number of bytes downloaded, and I'm not sure if there's a way to do that with the AWS SDK.
You can do:
using (var response = client.GetObject(request))
{
response.WriteObjectProgressEvent += Response_WriteObjectProgressEvent;
response.WriteResponseStreamToFile(#"C:\Downloads\file.exe");
}
private static void Response_WriteObjectProgressEvent(object sender, WriteObjectProgressArgs e)
{
Debug.WriteLine($"Tansfered: {e.TransferredBytes}/{e.TotalBytes} - Progress: {e.PercentDone}%");
}
Can you hook in to the WriteObjectProgressEvent object? If you subscribe to events from this object your function will be called multiple times during the download. It will receive the number of bytes that are downloaded/remaining so you can build a progress indicator.
I'm using Xamarin to build an Android app in c#.
The problem I'm having is that I need to load a part of an image without loading the whole image first. I have a rectangle of the region I want from the image.
I found this solution for normal Android : BitmapRegionDecoder
However when I try to invoke this class in my Xamarin project it's not there and I can't import it either.
I looked in the API and it says that it should be there.Android.Graphics.BitmapRegionDecoder documentation
Does anyone know if it's possible to use this class or if there is another way to achieve this?
Note that it says it is present in API level 10, hence you have to set your minimum target to 10 in the Application properties.
Then you can use it like so:
using (var inStream = ContentResolver.OpenInputStream(Android.Net.Uri.Parse("YourBitmapUri")))
{
using (var decoder = BitmapRegionDecoder.NewInstance(inStream, false))
{
var bitmap = decoder.DecodeRegion(YourRect, new BitmapFactory.Options());
// use your bitmap i.e. for an ImageView
bitmap.Dispose();
}
}