ZipEntry to Stream with monodroid - mono

I want to unzip a file in Android using Monodroid. I can get my ZipEntry with the Property NextEntry, but now I really need to convert this ZipEntry to a simple Stream.
EDIT:
Some part of my code
using System;
using System.IO;
using Java.Util.Zip;
using File = System.IO.File;
public void ExtractFile(Stream ZipFile, Action<String, Stream> WriteFile)
{
ZipInputStream zis;
try
{
zis = new ZipInputStream(ZipFile);
ZipEntry entry;
byte[] buffer = new byte[1024];
int count;
while ((entry = zis.NextEntry) != null)
{
// HERE I need to call my WriteFile action with a stream
}
...
Thanks

If you are using Ionic.Zip, then you can get it easily:
zipentry.InputStream

Related

AWS Lambda image/pdf upload to S3 is corrupted (asp.net core)

I have written a function that uploads a file in an s3 bucket. It works fine when I run my application locally.
But when I deploy the application in AWS Lambda, file upload is working properly but the file is being corrupted. The uploaded file size is a little bit higher than the actual file size.
txt file upload is working fine.
Here is my code
Guid guid = Guid.NewGuid();
string extension = System.IO.Path.GetExtension(logo.FileName);
var fileName = $"{guid}{extension}";
using (var ms = new System.IO.MemoryStream())
{
logo.CopyTo(ms);
ms.Position = 0;
System.IO.Stream stream = ms;
var client = new AmazonS3Client(AppConstants.S3AccessKey, AppConstants.S3SecretKey, Amazon.RegionEndpoint.USEast1);
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = AppConstants.S3Bucket,
Key = fileName,
InputStream = stream
};
PutObjectResponse response = await client.PutObjectAsync(putRequest);
}
I have configure API Gateway for binary data as well as change the LambdaEntryPoint with following code
RegisterResponseContentEncodingForContentType("multipart/form-data", ResponseContentEncoding.Base64);
Is there any other configuration that I missed?
I think you are not showing the full code you have written. I had the same issue yesterday.
I was using the System.Drawing.Image namespace to store the image and then I was resizing it. The problem with the System.Drawing.Image is that it is supported only on the Windows platform. That's why it was working from the local machine.
This is how I have solved this issue:
I had to install a third-party library called ImageSharp. The code is written below:
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Formats.Png;
public class Function
{
public MemoryStream GetReducedImage(int width, int height, MemoryStream resourceImage)
{
try
{
using (var image = Image.Load(resourceImage))
{
image.Mutate(x => x.Resize(width, height));
var ms = new MemoryStream();
image.Save(ms, new PngEncoder());
ms.Position = 0;
return ms;
}
}
catch (Exception e)
{
return null;
}
}
}

Blazor Server create link to download file from byte array

I have a method in my code behind to retrieve a get a pdf file from an API and return the byte[]
byte[] byteArray = response.Content.ReadAsByteArrayAsync().Result; ;
using (MemoryStream pdfStream = new MemoryStream())
{
pdfStream.Write(byteArray, 0, byteArray.Length);
pdfStream.Position = 0;
return new FileStreamResult(pdfStream, "application/pdf");
}
How in Blazor server to I create a link in my .razor component to consume this byte[] so that when the user clicks the link, it triggers the file download?
Your solution is close because you're creating the appropriate result, but you simply need the method that returns it.
Set up your API controller like the following:
[ApiController]
public class DownloadController : ControllerBase {
[HttpGet]
public ActionResult Get() {
byte[] byteArray = response.Content.ReadAsByteArrayAsync().Result; ;
using (MemoryStream pdfStream = new())
{
pdfStream.Write(byteArray, 0, byteArray.Length);
pdfStream.Position = 0;
var result = FileStreamResult(pdfStream, "application/pdf");
result.FileDownloadName = "sample.txt";
return result;
}
}
}

How to save a file from a windows store app in Unity

I'm making an app in Unity3D for release on the windows store.
It seems you cant write files using the .net streamwriter.
I'd like to save a csv file to a certain location and then later send it to a server using the WWW class.
I found a project which reads a file from the assets folder.
Heres the code for that...
using UnityEngine;
using System;
using System.Collections;
using System.IO;
#if NETFX_CORE
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
#endif
namespace IOS
{
public class File
{
public static object result;
#if NETFX_CORE
public static async Task<byte[]> _ReadAllBytes(string path)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path.Replace("/", "\\"));
byte[] fileBytes = null;
using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (DataReader reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
return fileBytes;
}
#endif
public static IEnumerator ReadAllText(string path)
{
#if NETFX_CORE
Task<byte[]> task = _ReadAllBytes(path);
while (!task.IsCompleted)
{
yield return null;
}
UTF8Encoding enc = new UTF8Encoding();
result = enc.GetString(task.Result, 0, task.Result.Length);
#else
yield return null;
result = System.IO.File.ReadAllText(path);
#endif
}
}
}
public class Example : MonoBehaviour
{
private string data;
IEnumerator ReadFile(string path)
{
yield return StartCoroutine(IOS.File.ReadAllText(path));
data = IOS.File.result as string;
}
public void OnGUI()
{
string path = Path.Combine(Application.dataPath, "StreamingAssets/Data.txt");
if (GUILayout.Button("Read file '" + path + "'"))
{
StartCoroutine(ReadFile(path));
}
GUILayout.Label(data == null ? "<NoData>" : data);
}
}
Heres the MSDN docs for serializing with Windows Store apps
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh758325.aspx
I'm wondering how to adapt this to suit my purposes. ie. Write a file to a specific location that I can reference later when I am sending the file via WWW.
The main issue is the location. The Application.dataPath is read only data within the app's package. To write data use Application.persistentDataPath to get a writable location in the application data folder.
Unity provides alternatives to System.IO.File with its UnityEngine.Windows.File object. You can just switch the using between System.IO and UnityEngine.Windows then call File.ReadAllBytes or File.WriteAllBytes regardless of platform.
This is essentially what your code snippit is doing, except that Unity already provides it.

transfer local database (SQILLIT) on the Web(internet) in xamarin cod C# for Android

I want to transfer my local database on the Web, Please help me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.IO;
using Mono.Data.Sqlite;
using Java.IO;
namespace Forooshgah
{
class cls_Connection
{
private static string DatabaseName = "DB_Forooshgah.db3";
private static string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
private static string DatabaseNameEndofYear;
private static Java.IO.File _dirBackup = new Java.IO.File(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Do2ta/backup");
public static string getConnectionString()
{
string db = Path.Combine (path, DatabaseName);
return db;
}
public static SqliteConnection setConnection()
{
var databasePath = Path.Combine(path, DatabaseName);
//return new SqliteConnection(String.Format("Data Source={0};Password={1}", databasePath, "test"));
return new SqliteConnection(String.Format("Data Source={0};", databasePath));
}
This code is "Upload File using FTP"
protected void Upload(string dbpath)
{
try
{
// Get the object used to communicate with the server.
string url = "ftp://xxx.xxx.xxx.xxx/xxx/xxx";
FtpWebRequest request =(FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","someone#somesite.com");
FileStream file = File.OpenRead(dbpath);
byte[] buffer = new byte[file.Length];
file.Read (buffer, 0, (int)file.Length);
file.Close ();
Stream ftpStream = request.GetRequestStream ();
ftpStream.Write (buffer, 0, buffer.Length);
ftpStream.Close ();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
catch(Exception exc)
{
}
}

How to convert a file to bytes and bytes to a file in mvc4

I am using MVC4. My requirement is:
I have to convert the file into byte array and save to database varbinary column.
For this I written code like below:
public byte[] Doc { get; set; }
Document.Doc = GetFilesBytes(PostedFile);
public static byte[] GetFilesBytes(HttpPostedFileBase file)
{
MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
return target.ToArray();
}
I am downloading the file by using the following code:
public ActionResult Download(int id)
{
List<Document> Documents = new List<Document>();
using (SchedulingServiceInstanceManager facade = new SchedulingServiceInstanceManager("SchedulingServiceWsHttpEndPoint"))
{
Document Document = new Document();
Document.DMLType = Constant.DMLTYPE_SELECT;
Documents = facade.GetDocuments(Document);
}
var file = Documents.FirstOrDefault(f => f.DocumentID == id);
return File(file.Doc.ToArray(), "application/octet-stream", file.Name);
}
when I am downloading pdf file then it is showing message as "There was an error opening this document. The file is damaged and could not be repaired."
Any thing else I need to do?
I tried with the following code but no luck
return File(file.Doc.ToArray(), "application/pdf", file.Name);
Please help me to solve the issue.
Thanks in advance.
Please try as in below code in your controller
FileStream stream = File.OpenRead(#"c:\path\to\your\file\here.txt");
byte[] fileBytes= new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();
//Begins the process of writing the byte array back to a file
using (Stream file = File.OpenWrite(#"c:\path\to\your\file\here.txt"))
{
file.Write(fileBytes, 0, fileBytes.Length);
}
It may helps you...