Open pdf from byte array ios xamarin c# - c#

I have a byte array that contains a pdf document and I want to open it in an ios application.
This is my code so far:
public static string WriteFileFromByteArray(string fileName, byte[] bytes)
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filePath = Path.Combine(documentsPath, fileName);
File.WriteAllBytes(fileName, bytes);
return filePath;
}
Does any one know how to do so?

Not sure where exactly you are stuck up.
But there is an issue in the below line of code you have posted.
File.WriteAllBytes(**fileName**, bytes);// on this code you are using filename instead of filepath.
Use filePath variable instead of fileName as it just contains the name of a file.
Refer the below link for PDF viewer.
http://forums.xamarin.com/discussion/631/open-a-pdf-with-the-built-in-pdf-viewer

Related

ASP.net download file Using HttpContext.Current.Response fileName

I am trying to download a file using System.Web.HttpContext.Current.Response using the following code:
HttpResponse objResponse = System.Web.HttpContext.Current.Response;
I am encoding the file name using:
FileName = Uri.EscapeDataString(FileName);
The file is downloading correctly, except when I have comma or dot in the file name.
In that case, while downloading the file, the explorer cannot decode the comma back.
For instance:
Original file name: Testing, File
Encoded name: Testing%2C%20file
Downloaded file name: Testing%2C file
Is there any way to code/encode the file name, in order to keep the commas and dots?
for example, you can use:
public ActionResult DownloadFileXML(string filePath)
{
string fileName = Path.GetFileName(filePath);
return File(filePath, "application/xml", fileName);
}

Converting full path of Image to binary

firstly, yes I know it might be a duplicate question, but really, I have applied all possible answers but nothing worked.
What I want is to convert an image selected by the user to binary format, and I'm using asp.net/c# to do such method.
Look at my codes first to do this:
if (FileUpload1.HasFile)
{
pressNumberOfTimes++;
string strname = Path.GetFileName(FileUpload1.PostedFile.FileName);
lbl_homeCarouselAdd.ID = "lbl_homeCarouselAdd" + pressNumberOfTimes;
strDiv.Append(string.Format(strname) + ",");
FileUpload1.PostedFile.SaveAs(HttpContext.Current.Server.MapPath("~/upload/") + strname);
string fullImagePath = HttpContext.Current.Server.MapPath("~/upload/") + strname;
byte[] imgdata = File.ReadAllBytes(fullImagePath);
var a = String.Join(",", lbl_homeCarouselAdd.Text += strDiv.ToString());
from what I have seen from the answers in this website and others to convert image to binary is to use this code:
byte[] imgdata = File.ReadAllBytes(fullImagePath);
which I have used in my codes.
However, all I get is an empty value for the binary, while "fullImagePath" variable holds the full bath of the selected image.
I have also used the following method, but it gave me the same empty result:
public static byte[] ImageToBinary(string _path)
{
FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read);
byte[] b = new byte[fS.Length];
fS.Read(b, 0, (int)fS.Length);
fS.Close();
return b;
}
For more info:
This is how my web form looks like
so, the user can upload an image and then click "save image" button in order to save the selected event, and here the website should convert the image to binary format.
Concerns:
Is it possible that "upload" folder in my "VS" project is not refreshed with the new selected image is the reason behind the empty value??
Is it possible that permissions among c:\ directory is causing such error?? because I'm working on a machine given by the company I work for, and I did face some issues before regarding this.
if(FileUpload1.HasFile)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string extension = Path.GetExtension(filename);
string contentType = FileUpload1.PostedFile.ContentType;
HttpPostedFile file = FileUpload1.PostedFile;
byte[] imgdata= new byte[file.ContentLength];
file.InputStream.Read(imgdata, 0, file.ContentLength);
}

Convert Microsoft.Office.Interop.Excel.Application to byte[]

I am creating a excel file in the code as Shown Below
Microsoft.Office.Interop.Excel.Application excelFile = CreateExcelFile();
now I want to convert this excelFile to byte[] without saving to hard drive. How is it possible?
had the same problem some time ago. You have to create a temporary file, and then read it to a byte array.
Example code:
string tempPath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + "_temp";//date time added to be sure there are no name conflicts
workbook.SaveAs(tempPath, workbook.FileFormat);//create temporary file from the workbook
tempPath = workbook.FullName;//name of the file with path and extension
workbook.Close();
byte[] result = File.ReadAllBytes(tempPath);//change to byte[]
File.Delete(tempPath);//delete temporary file
That isn't an Excel File it is a COM object used for Excel Automation. It can be used to request Excel to save a document to disk (as a temporary file), which you could then load into a byte[] and then delete the temporary file.
The following code could be used to do this for the active workbook:
public byte[] GetActiveWorkbook(Microsoft.Office.Interop.Excel.Application app)
{
string path = Path.GetTempFileName();
try
{
app.ActiveWorkbook.SaveCopyAs(path);
return File.ReadAllBytes(path);
}
finally
{
if(File.Exists(path))
File.Delete(path);
}
}

Returning An Xml String To Client Code From C#

I am reading a file from the user files that contains xml that I am processing in a Generic Handler and then passing to the client.
The problem I am having is when I pass the string of xml to the client. Its not in the proper format. It removes the root tag and "<xml 1.0>" tag entirely when looking at it through the client code.
I am looking for some code to preserve the xml string as is when it gets to the client.
I am reading the xml out of a file using System.IO on the server..
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
string path = context.Server.MapPath("~/Temp");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var file = context.Request.Files[0];
string fileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string strFileName = fileName;
fileName = Path.Combine(path, fileName);
file.SaveAs(fileName);
string msg = File.ReadAllText(fileName);
File.Delete(fileName);
context.Response.Write(msg);
}
}
The xml always starts at "Gambardella..." For some reason it cannot read the beginning of the file when being send to the cient.
Here is an image of the sample xml..
The data is sent out of the handler fine but the client cuts off the top information. It looks like the plugin I am using is storing the (or getting) the data from an iframe. Could the iframe maybe be the culprit in cutting off the beginning xml??
The sample client code I am using is here
You can simply use Response.WriteFile, instead of reading the file then sending it.
Response.WriteFile(fileName);
This will return the contents of the file with the correct HTTP Content-Type header. If the file has the XML declaration, it will not remove it.
Something like the following, based on your code and untested (an without a MemoryStream, as it is not needed in this case):
var file = context.Request.Files[0];
file.InputStream.CopyTo(context.Response.OutputStream)

Change File Extension Using C#

I have many file types: pdf, tiff, jpeg, bmp. etc.
My question is how can I change file extension?
I tried this:
my file= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
myfile.replace(extension,".Jpeg");
No matter what type of file it is, the format I specify must be with the file name. But it does not work. I get file path from browser like c:\..\..\a.jpg, and the file format is a.jpeg. So, when I try to delete it, it gives me an error: Cannot find the file on specified path'. So, I am thinking it has something to do with the file extension that does not match. So, I am trying to convert .jpg to .jpeg and delete the file then.
There is: Path.ChangeExtension method. E.g.:
var result = Path.ChangeExtension(myffile, ".jpg");
In the case if you also want to physically change the extension, you could use File.Move method:
File.Move(myffile, Path.ChangeExtension(myffile, ".jpg"));
You should do a move of the file to rename it. In your example code you are only changing the string, not the file:
myfile= "c:/my documents/my images/cars/a.jpg";
string extension = Path.GetExtension(myffile);
myfile.replace(extension,".Jpeg");
you are only changing myfile (which is a string). To move the actual file, you should do
FileInfo f = new FileInfo(myfile);
f.MoveTo(Path.ChangeExtension(myfile, ".Jpeg"));
See FileInfo.MoveTo
try this.
filename = Path.ChangeExtension(".blah")
in you Case:
myfile= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
filename = Path.ChangeExtension(myfile,".blah")
You should look this post too:
http://msdn.microsoft.com/en-us/library/system.io.path.changeextension.aspx
The method GetFileNameWithoutExtension, as the name implies, does not return the extension on the file. In your case, it would only return "a". You want to append your ".Jpeg" to that result. However, at a different level, this seems strange, as image files have different metadata and cannot be converted so easily.
Convert file format to png
string newfilename ,
string filename = "~/Photo/" + lbl_ImgPath.Text.ToString();/*get filename from specific path where we store image*/
string newfilename = Path.ChangeExtension(filename, ".png");/*Convert file format from jpg to png*/
Alternative to using Path.ChangeExtension
string ChangeFileExtension(ReadOnlySpan<char> path, ReadOnlySpan<char> extension)
{
var lastPeriod = path.LastIndexOf('.');
return string.Concat(path[..lastPeriod], extension);
}
string myfile= #"C:/my documents/my images/cars/a.jpg";
string changedFileExtesion = ChangeFileExtension(myfile, ".jpeg");
Console.WriteLine(changedFileExtesion);
// output: C:/my documents/my images/cars/a.jpeg

Categories