Sending an Image from the Client to the Server - c#

So, I am trying to send an image between the server and client, however, somehow when the server receives the image, the image does not render all of it.
Client Side code:
//button click
Bitmap tImage = new Bitmap(#"C:\Users\Milan\Downloads\guitarstill.gif");
byte[] bStream;
//if (string.IsNullOrEmpty(tbPayload.Text)) return;
try
{
bStream = imageToByteArray(tImage);
if (mTcpClient != null)
{
if (mTcpClient.Client.Connected)
{
mTcpClient.GetStream().BeginWrite(imageToByteArray(tImage), 0, imageToByteArray(tImage).Length, onCompleteWriteToServer, mTcpClient);
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
//Within another method:
public byte[] imageToByteArray(System.Drawing.Image imageIn) {
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
//richTextBox1.Text = ms.ToArray().ToString();
return ms.ToArray();
}
Server Side Code:
void onCompleteReadFromTCPClientStream(IAsyncResult iar)
{
TcpClient tcpc;
int nCountReadBytes = 0;
string strRecv;
ClientNode cn = null;
try
{
lock (mlClientSocks)
{
tcpc = (TcpClient)iar.AsyncState;
cn = mlClientSocks.Find(x => x.strId == tcpc.Client.RemoteEndPoint.ToString());
nCountReadBytes = tcpc.GetStream().EndRead(iar);
if (nCountReadBytes == 0)// this happens when the client is disconnected
{
MessageBox.Show("Client disconnected.");
mlClientSocks.Remove(cn);
lbClients.Items.Remove(cn.ToString());
return;
}
strRecv = Encoding.ASCII.GetString(cn.Rx, 0, nCountReadBytes);
//strRecv = Encoding.ASCII.GetString(mRx, 0, nCountReadBytes);
if (strRecv.StartsWith("GIF"))
{
//MemoryStream ms = new MemoryStream(cn.Rx);
//Image x = (Bitmap)((new ImageConverter()).ConvertFrom(cn.Rx));
pictureBox1.Image = byteArrayToImage(cn.Rx);
/*
lock (mlClientSocks)
{
//if (cn != null && cn.tclient != null && cn.tclient.Client.Connected)
//{
//foreach (var clients in spectatorsIPAndPort)
//{
cn = mlClientSocks.Find(x => x.strId == clients);
cn.Tx = new byte[512];
cn.Tx = Encoding.ASCII.GetBytes(strRecv);
cn.tclient.GetStream().BeginWrite(cn.Tx, 0, cn.Tx.Length, onCompleteWriteToClientStream, cn.tclient);
//Console.WriteLine("Sent Number of Clients via Request: " + Encoding.UTF8.GetString(cn.Tx) + " To " + clients);
//}
//}
}
*/
//printLine(DateTime.Now + " - " + cn.ToString() + ": " + strRecv);
}
cn.Rx = new byte[512];
tcpc.GetStream().BeginRead(cn.Rx, 0, cn.Rx.Length, onCompleteReadFromTCPClientStream, tcpc);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
lock (mlClientSocks)
{
printLine("Client disconnected: " + cn.ToString());
mlClientSocks.Remove(cn);
lbClients.Items.Remove(cn.ToString());
}
}
}
//within another method
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn, 0, byteArrayIn.Length);
//ms.Position = 0;
Image returnImage = Image.FromStream(ms);
return returnImage;
}
My Output:
Expected output: - this full image

Related

How to convert object in byte[] c#

CONVERT OBJECT TO BYTE[]
Hello how are you? I'm having difficulties in converting an object (returned by a query to the Postgres database) to byte[], I test in several different ways but I can't get the total size of the array stored in the database referring to the image. I have a single image saved in the database, and in each way I try to retrieve it, the byte[] comes with a different size depending on how I do the conversion from object to byte[]. The biggest array size I got was length = 42, the image has length = 675486. I've tried these ways.
using (conexao)
{
string sQL = " SELECT p.photo_img " +
" FROM empresa as e, photo as p " +
" WHERE e.empresa_img = " + id + " AND " +
" e.empresa_img = p.photo_id; ";
using (var command = new NpgsqlCommand(sQL, conexao))
{
byte[] productImageByte = null;
conexao.Open();
var rdr = command.ExecuteReader();
while (rdr.Read())
{
productImageByte = (byte[])rdr[0];
}
rdr.Close();
if (productImageByte != null)
{
using (MemoryStream productImageStream = new MemoryStream(productImageByte))
{
ImageConverter imageConverter = new System.Drawing.ImageConverter();
pct_Imagem.Image = imageConverter.ConvertFrom(productImageByte) as System.Drawing.Image;
}
}
}
}
The result of this was length = 13
private void dgv_empresa_CellClick(object sender, DataGridViewCellEventArgs e)
{
int id = Convert.ToInt32(dgv_empresa.SelectedCells[0].OwningRow.Cells[9].Value);
if (id != 0)
{
try
{
string query = " SELECT p.photo_img " +
" FROM empresa as e, photo as p " +
" WHERE e.empresa_img = " + id + " AND " +
" e.empresa_img = p.photo_id; ";
conexao.Open();
DataTable dados = new DataTable();
NpgsqlDataAdapter adaptador = new NpgsqlDataAdapter(query, conexao);
adaptador.Fill(dados);
if (dados.Rows.Count > 0)
{
foreach (DataRow linha in dados.Rows)
{
byte[] data = ObjectToByteArray(linha[0]);
var imagem = (Image)new ImageConverter().ConvertFrom(data);
pct_Imagem.Image = imagem;
}
}
}
catch (Exception ex)
{
conexao.Close();
MessageBox.Show(ex.Message, "Erro no Banco de Dados!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
conexao.Close();
}
}
}
byte[] ObjectToByteArray(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
The result of this was length = 42
These last two brought me the best results. But still, it's not a valid byte array. Can someone help me?
you can use this method that I serialized the class into JSON text and then converted it to byte[]. You can either serialize it to XML
private byte[] CreateByteArray(object obj)
{
using var memoryStream = new MemoryStream();
using var writer = new StreamWriter(memoryStream);
var jsonText = JsonConvert.SerializeObject(obj);
writer.WriteAsync(jsonText);
writer.Flush();
return memoryStream.ToArray();
}
I managed to do, what I needed to adjust to not use Connetion, but create and discard in each block that was to be used

How to retrieve byte array to image c#

I'm trying to retrieve an image saved in postgresql database in BYTEA format, but I'm having difficulties in transforming the byte array to image using C#. I'm getting "INVALID PARAMETERS" as a return. I've been trying for days and still haven't been able to. Can anyone help me?
byte[] ObjectToByteArray(object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
try
{
using (MemoryStream mStream = new MemoryStream(byteArrayIn))
{
return Image.FromStream(mStream);
}
}
catch (Exception)
{
throw;
}
}
private void dgv_empresa_CellClick(object sender, DataGridViewCellEventArgs e)
{
int id = Convert.ToInt32(dgv_empresa.SelectedCells[0].OwningRow.Cells[9].Value);
if (id != 0)
{
try
{
string query = " SELECT p.photo_img " +
" FROM empresa as e, photo as p " +
" WHERE e.empresa_img = " + id + " AND " +
" e.empresa_img = p.photo_id; ";
conexao.Open();
dgv_empresa.Rows.Clear();
DataTable dados = new DataTable();
NpgsqlDataAdapter adaptador = new NpgsqlDataAdapter(query, conexao);
adaptador.Fill(dados);
Image imagem = null;
if (dados.Rows.Count > 0)
{
foreach (DataRow linha in dados.Rows)
{
byte[] binary = ObjectToByteArray(linha[0]);
MemoryStream ms = new MemoryStream(binary, 0, binary.Length);
ms.Position = 0;
imagem = Image.FromStream(ms, true);
Image i = byteArrayToImage(binary);
}
}
pct_Imagem.Image = imagem;
}
catch (Exception ex)
{
conexao.Close();
MessageBox.Show(ex.Message, "Erro no Banco de Dados!", MessageBoxButtons.OK, MessageBoxIcon.Error);
//dgv_empresa.Rows.Clear();
}
finally
{
conexao.Close();
}
}

C# pass data between functions

I'm trying to write a code that will write the data coming from an external device (USB) to a file. I have a function that receives data in a separate task ReadAvailable and I don't know how to pass this data in a correct way to the SaveRxDataToFile function. The write function must also know how much data it is adding each time to the file in order to know when to end the write.
(I'm learning and maybe it's something simple, but I'm a little lost)
Could you please help?
Here is the code:
using FTD2XX_NET;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
namespace Engine
{
public class FtdiFifo
{
private FTDI ftHandle = new FTDI();
private FTDI.FT_DEVICE_INFO_NODE[] deviceInfos = new FTDI.FT_DEVICE_INFO_NODE[2];
public byte[] RxDataBuffer { get; set; } = new byte[65536];
public List<string> serialNumbers { get; set; }
public FtdiFifo()
{
System.Diagnostics.Debug.WriteLine("This is a new FtdiFifo object.");
serialNumbers = new List<string>();
}
public void IdentifyDevice()
{
FTDI.FT_STATUS ftdiStatus;
uint ftdiDeviceCount = 0;
serialNumbers.Clear();
ftdiStatus = ftHandle.GetNumberOfDevices(ref ftdiDeviceCount);
if (ftdiDeviceCount > 0)
{
System.Diagnostics.Debug.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString());
}
else if (ftdiDeviceCount == 0) // If no devices available, return
{
System.Diagnostics.Debug.WriteLine("No FTDI device detected (" + ftdiStatus.ToString() + ")");
return;
}
ftdiStatus = ftHandle.GetDeviceList(deviceInfos);
if (ftdiStatus == FTDI.FT_STATUS.FT_OK)
{
for (UInt32 i = 0; i < ftdiDeviceCount; i++)
{
System.Diagnostics.Debug.WriteLine("Device Index: " + i.ToString());
System.Diagnostics.Debug.WriteLine("Flags: " + String.Format("{0:x}", deviceInfos[i].Flags));
System.Diagnostics.Debug.WriteLine("Type: " + deviceInfos[i].Type.ToString());
System.Diagnostics.Debug.WriteLine("ID: " + String.Format("{0:x}", deviceInfos[i].ID));
System.Diagnostics.Debug.WriteLine("Location ID: " + String.Format("{0:x}", deviceInfos[i].LocId));
System.Diagnostics.Debug.WriteLine("Serial Number: " + deviceInfos[i].SerialNumber.ToString());
System.Diagnostics.Debug.WriteLine("Description: " + deviceInfos[i].Description.ToString());
System.Diagnostics.Debug.WriteLine("");
serialNumbers.Add(deviceInfos[i].SerialNumber.ToString());
}
}
return;
}
public void SetFifoMode()
{
FTDI.FT_STATUS ftStatus;
ftStatus = ftHandle.OpenBySerialNumber(serialNumbers[1]);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
System.Diagnostics.Debug.WriteLine("Cannot open device");
return;
}
ftStatus = ftHandle.SetTimeouts(5000, 5000);
System.Threading.Thread.Sleep(100);
ftStatus = ftHandle.SetBitMode(0xff, 0x00);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
System.Diagnostics.Debug.WriteLine("Cannot set bit mode");
return;
}
System.Threading.Thread.Sleep(100);
ftStatus = ftHandle.SetBitMode(0xff, 0x40);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
System.Diagnostics.Debug.WriteLine("Cannot set ftStatus");
return;
}
System.Threading.Thread.Sleep(100);
ftStatus = ftHandle.SetLatency(2);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
System.Diagnostics.Debug.WriteLine("Cannot set latency");
return;
}
System.Threading.Thread.Sleep(100);
ftStatus = ftHandle.InTransferSize(0x10000);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
System.Diagnostics.Debug.WriteLine("Cannot set In transfer size");
return;
}
System.Threading.Thread.Sleep(100);
ftStatus = ftHandle.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0, 0);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
System.Diagnostics.Debug.WriteLine("Cannot set flow control");
return;
}
System.Threading.Thread.Sleep(100);
ftStatus = ftHandle.Purge(FTDI.FT_PURGE.FT_PURGE_RX);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
{
System.Diagnostics.Debug.WriteLine("Cannot purge FTDI");
return;
}
System.Diagnostics.Debug.WriteLine("Synchronous FIFO mode enabled for " + serialNumbers[1]);
// Create a task and supply a user delegate by using a lambda expression.
Task taskA = new Task(() => ReceiveLoop());
// Start the task.
taskA.Start();
System.Diagnostics.Debug.WriteLine("ReceiveLoop enabled");
}
public bool IsDeviceAllowed(string allowedDevice)
{
foreach (string device in serialNumbers)
{
if (device == allowedDevice)
{
System.Diagnostics.Debug.WriteLine("Allowed device");
return true;
}
}
System.Diagnostics.Debug.WriteLine("No allowed device");
return false;
}
void ReadAvailable()
{
FTDI.FT_STATUS ftStatus;
UInt32 numBytesAvailable = 0;
ftStatus = ftHandle.GetRxBytesAvailable(ref numBytesAvailable);
System.Diagnostics.Debug.WriteLine(ftStatus + " bytes available: " + numBytesAvailable.ToString());
if (numBytesAvailable < 1)
{
System.Diagnostics.Debug.WriteLine("NO_READ_DATA_AVAILABLE\n");
return;
}
byte[] bytes = new byte[numBytesAvailable];
UInt32 numBytesRead = 0;
ftHandle.Read(bytes, numBytesAvailable, ref numBytesRead);
if (numBytesAvailable != numBytesRead)
System.Diagnostics.Debug.WriteLine("Something bad happened");
System.Diagnostics.Debug.WriteLine("Dec: " + String.Join(" ", bytes) + "\nHex: " + BitConverter.ToString(bytes).Replace("-", string.Empty) + "\nText: " + Encoding.Default.GetString(bytes) + "\n");
}
public void ReceiveLoop()
{
var receivedDataEvent = new AutoResetEvent(false);
ftHandle.SetEventNotification(FTDI.FT_EVENTS.FT_EVENT_RXCHAR, receivedDataEvent);
//var cancellation = new CancellationTokenSource(); // should be declared in a broader scope
//while (!_cancellation.IsCancellationRequested)
while (true)
{
receivedDataEvent.WaitOne();
ReadAvailable();
}
}
public void SaveRxDataToFile(byte[] rxData)
{
String filename = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_readout") + ".bin";
const int dataLengthTotal = 1024000;
int dataLength = 0;
do
{
using (var fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.Write))
{
fileStream.Write(rxData, dataLength, rxData.Length);
}
dataLength += rxData.Length;
} while (dataLength < dataLengthTotal);
}
}
}

Problem with Sign PDF by SHA1 when use iTextSharp

I have a digital signature problem with PDF files, the process is as follows:
- I have a PDF file on the Server, then I locate the signature and convert it to byte format [] with SHA1.
- The client will retrieve the signature from the USB token to assign to byte [] transmitted from the server.
- I then returned the server to assign the signature.
But when I code as below, the program still runs normally without error, but the USB signature contents are not signed into the pdf file. Please help me to fix it.
private void Form1_Load(object sender, EventArgs e)
{
string UnsingnedPdf = #"E:\PrintContractAdviceNote.pdf";
string TempPdf = #"E:\PrintContractAdviceNote_TMP.pdf";
string singnedPdf = #"E:\PrintContractAdviceNote_Sign.pdf";
PDFSigning cl = new PDFSigning();
cl.GetBytesToSign(UnsingnedPdf, TempPdf, singnedPdf, "CHUKY1", 3, "BIG BEAR");
}
public static X509Certificate2 selectCert()
{
X509Certificate2 certificate = null;
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
if (store.Certificates.Count == 1)
{
//Return the certificate present.
certificate = store.Certificates[0];
}
else if (store.Certificates.Count > 0)
{
// Request the user to select a certificate
try
{
var certificates = X509Certificate2UI.SelectFromCollection(store.Certificates,
"Digital Certificates", "Select a certificate from the following list:",
X509SelectionFlag.SingleSelection);
// Check if one has been returned
if (certificates.Count == 1)
{
certificate = certificates[0];
var newCert = new X509Certificate2(certificate.RawData, "mypassword");
}
else
{
throw new ArgumentException("Please select a certificate to publish PnL to Flash");
}
}
catch (Exception ex)
{
}
}
else
{
throw new ArgumentException("There is no certificate available to publish PnL to flash, please contact support.");
}
}
finally
{
store.Close();
}
return certificate;
}
public class IpInfo
{
//country
public string Country { get; set; }
}
public byte[] GetBytesToSign(string unsignedPdf, string tempPdf, string signedPdf, string signatureFieldName, Int16 iType, string SignName)
{
if (File.Exists(tempPdf))
File.Delete(tempPdf);
if (File.Exists(signedPdf))
File.Delete(signedPdf);
byte[] array = null;
bool Islock = true;
FileStream os = File.OpenWrite(tempPdf);
PdfReader reader = new PdfReader(unsignedPdf);
DateTime dt = DateTime.Now;
using (PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0'))
{
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.Contact = "www.marico.com";
appearance.SignDate = dt;
//BaseFont bf = BaseFont.CreateFont(HttpContent.Current.Server.MapPath("~/Resources/Font/arial.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//Font font = new Font(bf, 8);
//appearance.Layer2Font = font;
appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
appearance.Acro6Layers = true;
appearance.Layer2Text = "Signed by:" + Environment.NewLine + " " + SignName + Environment.NewLine + "Date :" + Environment.NewLine + " " + dt.ToShortDateString() + " " + dt.ToShortTimeString();
Image img;
if (iType == 3)
{
img = Image.GetInstance(#"E:\Tài liệu\Marico\HINH ANH\talent.png");
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(15, 50, 235, 95), reader.NumberOfPages, signatureFieldName);
}
else
{
img = Image.GetInstance(#"E:\Tài liệu\Marico\HINH ANH\talent.png");
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(350, 50, 570, 95), reader.NumberOfPages, signatureFieldName);
}
appearance.SignatureGraphic = img;
IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
MakeSignature.SignExternalContainer(appearance, external, 8192);
array = SHA1.Create().ComputeHash(appearance.GetRangeStream());
stamper.Dispose();
stamper.Close();
}
if (iType != 3)
{
while (Islock)
{
reader.Dispose();
reader.Close();
os.Dispose();
os.Close();
Islock = IsFileLocked(unsignedPdf);
}
}
else
{
reader.Dispose();
reader.Close();
os.Dispose();
os.Close();
}
X509Certificate2 cert = selectCert();
RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(cert.PrivateKey);
formatter.SetHashAlgorithm("SHA1");
byte[] signature = formatter.CreateSignature(array);
EmbedSignature(tempPdf, signedPdf, signatureFieldName, signature);
return (array);
}
public static bool IsFileLocked(string pathfile)
{
try
{
using (FileStream fs = new FileStream(pathfile, FileMode.Open))
{
fs.Dispose();
fs.Close();
}
return false;
}
catch (IOException ex)
{
return true;
}
}
private static void SetSigPosition(PdfSignatureAppearance sigAppearance, int oldSigCount, string signatureFieldName, int numpage = 1)
{
float llx = (200 + 20) * (oldSigCount % 5) + 20,
lly = (25 + 20) * (oldSigCount / 5) + 5,
urx = llx + 200,
ury = lly + 45;
}
public void EmbedSignature(string tempPdf, string signedPdf, string signatureFieldName, byte[] signedBytes)
{
IExternalSignatureContainer external = new MyExternalSignatureContainer(signedBytes);
using (FileStream os = File.OpenWrite(signedPdf))
{
using (PdfReader reader = new PdfReader(tempPdf))
{
MakeSignature.SignDeferred(reader, signatureFieldName, os, external);
reader.Dispose();
reader.Close();
os.Dispose();
os.Close();
}
}
}
private class MyExternalSignatureContainer : IExternalSignatureContainer
{
private readonly byte[] signedBytes;
public MyExternalSignatureContainer(byte[] signedBytes)
{
this.signedBytes = signedBytes;
}
public byte[] Sign(Stream data)
{
return signedBytes;
}
public void ModifySigningDictionary(PdfDictionary signDic)
{
}
}

How to copy one TXT File from Assets folder to SD / Internal Storage Android C# Xamarin

I am trying to Copy a TXT File in Assets over to the SD Card / Internal Storage.
All examples are in Java, is there anyway this can be done in C#?
Java Code:
final static String TARGET_BASE_PATH = "/sdcard/appname/voices/";
private void copyFilesToSdCard() {
copyFileOrDir(""); // copy all files in assets folder in my project
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir( p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
}
How would the above code be done in C#?
Thanks.
A possible solution could look like my method to copy a database from the Assets folder to the device:
public static async Task CopyDatabaseAsync(Activity activity)
{
var dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "YOUR_DATABASENAME");
if (!File.Exists(dbPath))
{
try
{
using (var dbAssetStream = activity.Assets.Open("YOUR_DATABASENAME"))
using (var dbFileStream = new FileStream(dbPath, FileMode.OpenOrCreate))
{
var buffer = new byte[1024];
int b = buffer.Length;
int length;
while ((length = await dbAssetStream.ReadAsync(buffer, 0, b)) > 0)
{
await dbFileStream.WriteAsync(buffer, 0, length);
}
dbFileStream.Flush();
dbFileStream.Close();
dbAssetStream.Close();
}
}
catch (Exception ex)
{
//Handle exceptions
}
}
}
You can call it in OnCreate with ContinueWith
CopyDatabaseAsync().ContinueWith(t =>
{
if (t.Status != TaskStatus.RanToCompletion)
return;
//your code here
});

Categories