I'm trying to save a piture recovered from a byte[] on the asp.net server. Here is my code :
MemoryStream ms = new MemoryStream(cli.LOGO, 0, cli.LOGO.Length);
ms.Write(cli.LOGO, 0, cli.LOGO.Length);
string thePath = Server.MapPath("~/App_Data");
string wholePath = thePath + "\\logo.jpg";
FileStream fs = new FileStream(wholePath, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(cli.LOGO);
bw.Close();
Where cli.LOGO is a byte array. I'm just trying to save it as a .jpg image in my App_Data folder (or anything else of course) but... It's doing nothing. cli.LOGO is not empty, but the file is not created... Why so ? Is it the proper way to save an image ? Thanks !
Try like this which is a bit shorter than your code:
string path = Server.MapPath("~/App_Data/logo.jpg");
File.WriteAllBytes("file", cli.LOGO);
try doing this
if (Request.Files["Photo"] != null)
{
string path = "/uploads/" + DateTime.Now.Ticks.ToString() + "_" + Request.Files["Photo"].FileName;
Request.Files["Photo"].SaveAs(Server.MapPath(path));
SP.PhotoPath = path;
//The MapPath method maps the specified relative or virtual path to the
//corresponding physical directory on the server.
}
Related
following is the code added:
The image object is in the library.imaging.
"using System.Drawing;"
"using System.Drawing.Imaging;"
{
byte[] b = Convert.FromBase64String("R0lGODlhAQABAIAAA");
Image image;
using (MemoryStream memstr = new MemoryStream(b))
{
image = Image.FromStream(memstr);
}
}
Here is the new code I'm working on:
{
string base64BinaryStr = " ";
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
string s = Encoding.UTF8.GetString(PDFDecoded);
}
So this is your current code:
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
You don't actually need BinaryWriter for this. File.Create already gives you a FileStream:
FileStream writer = File.Create(FileName + ".pdf");
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
But this will still have the problem you're experiencing because you're not flushing the data to it. We also need to close the file. Thankfully, we can wrap it in using and it will do both for us:
using (FileStream writer = File.Create(FileName + ".pdf"))
{
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
}
But a simpler way to do this is:
File.WriteAllBytes(FileName + ".pdf", PDFDecoded);
As for PDF -> Image, you'll probably have to see if there is a library available for this (search "PDF to Image NuGet") that can help you with this as I don't think there is anything built-in.
Just a thought, you don't need to create a physical PDF file, you can have it in memory and convert it to image from there.
Now the problem is that you cannot use Image from System.Drawing.Imaging for this, it doesn't support reading PDF file.
Instead you'll need to search for some library that can do that.
For example, try GemBox.Pdf, you can use it like this:
string base64String = "...";
byte[] pdfBytes = Convert.FromBase64String(base64String);
using (PdfDocument pdfDocument = PdfDocument.Load(new MemoryStream(pdfBytes)))
{
ImageSaveOptions imageOptions = new ImageSaveOptions(ImageSaveFormat.Png);
string imageName = DateTime.Now.ToString("dd-MM-yyyy-hh-mm") + ".png";
pdfDocument.Save(#"C:\Users\Downloads\" + imageName, imageOptions);
}
I've used the code provided on this Convert example.
How can I get a file from external path same as "file://A/B/C/D/"
In local machine I have access to the path of "file://" but the user has not access.
Now I want to read some files from "file://A/B/C/D/" and make downloadable for user.
How can I do it?
(current directory is "https://localhost:44331/")
public async Task<IActionResult> DownloadDocument(string berichtsnummer)
{
var constantPath = "file://A/B/C/D/";
using (FileStream fileStream = System.IO.File.OpenRead(constantPath))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
return File(fileStream, "application/octet-stream");
}
}
when I click to download link, I get this error:
"IOException: The syntax for filename, directory name, or volume label
is incorrect:"
[
A view of path "file://A/B/C/D/":
A local file path is not "file://". You can read the file normally using the local file path as
var path = "C:\\...";
and then send to content to the client browser.
If the file is not on the local machine, the only way is to access it using a network share. You can then use UNC paths, like
var path = #"\\Server\Path\...";
That's important to change the constantPath to "\\\\A\\B\\C\\D\\"
private string[] GetListOfDocumentLink()
{
string path = string.Empty;
string constantPath = "\\\\A\\B\\C\\D\\";
string folderName = string.Empty;
string year = string.Empty;
// determine folderName and year.
path = constantPath
+ Path.DirectorySeparatorChar.ToString()
+ folderName
+ Path.DirectorySeparatorChar.ToString()
+ year;
var filter = Berichtsnummer + "*.pdf";
string[] allFiles = Directory.GetFiles(path, filter);
return allFiles;
}
Now you can send the path to DownloadDocument method:
public async Task<IActionResult> DownloadDocument(string path)
{
byte[] berichtData = null;
FileInfo fileInfo = new FileInfo(path);
long berichtFileLength = fileInfo.Length;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
berichtData = br.ReadBytes((int)berichtFileLength);
return File(berichtData, MimeTypeHelper.GetMimeType("pdf"));
}
I'm using a C# wrapper to convert PDFs to images using Ghostscript, however i cant seem to reference the dll correctly.
I have the DLL stored in the bin folder (also don't know if that's the best place to keep it there or not)
Here's my code:
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
Ghostscript.NET.Rasterizer.GhostscriptRasterizer rasterizer = null;
Ghostscript.NET.GhostscriptVersionInfo vesion = new Ghostscript.NET.GhostscriptVersionInfo(new Version(0, 0, 0), path + #"\gsdll64.dll", string.Empty, Ghostscript.NET.GhostscriptLicense.GPL);
Stream inStream = new MemoryStream(fileData);
MemoryStream outStream = new MemoryStream();
List<Image> imageList = new List<Image>();
using (rasterizer = new Ghostscript.NET.Rasterizer.GhostscriptRasterizer())
{
rasterizer.Open(inStream, vesion, false);
for (int i = 1; i <= rasterizer.PageCount; i++)
{
//string pageFilePath = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(file) + "-p" + i.ToString() + ".jpg");
int dpi = 200;
Image img = rasterizer.GetPage(dpi, dpi, i);
img.Save(outStream, ImageFormat.Jpeg);
Image img = new Image
{
imgByteArray = outStream.ToArray()
};
imageList.Add(image);
}
rasterizer.Close();
}
I'm getting the Ghostscript native library could not be found error.
Here's the path I get
I think it has to do with the double / and 'file://' in the DLLPath string. And should I also specify the LipPath as well?
Any help??
In your case you should make ghostscript dll path this way:
string binPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string gsDllPath = Path.Combine(binPath, Environment.Is64BitProcess ? "gsdll64.dll" : "gsdll32.dll");
Even though this does not answer the question directly, I think it's worth mentioning, because I've ran into a problem using the OP's code with Ghostscript.NET version 1.2.1 published in 2016. Here's the fix I found:
In the source code,
Ghostscript.NET\Helpers\StreamHelper.cs:171
n = output.Read(buffer, 0, buffer.Length);
really should've been
n = input.Read(buffer, 0, buffer.Length);
If you're opening a stream instead of a path, without modifying the above mentioned code, you'll get empty result because the input stream did not get copied.
Reading into the code in more depth finds that the input stream is written into a temp file then read again into memory. You'll be better off just using rasterizer.Open by the path instead of stream, if it were a PDF file on disk to begin with.
I am developing an application which store filename in database. For Mozilla & Chrome it is showing FileName only but in IE it is showing full path of file. Now I want to check whether given filename is filename or filepath. Is there any way to do it?
Here is my code:
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
byte[] image = null;
var file = attachments.First();
// Some browsers send file names with full path. We only care about the file name.
string filePath = Server.MapPath(General.FaxFolder + "/" + file.FileName);
file.SaveAs(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using (BinaryReader br = new BinaryReader(fs))
{
image = br.ReadBytes((int)fs.Length);
}
TempData["Image"] = image;
System.IO.File.Delete(filePath);
return Json(new { status = "OK", imageString = Convert.ToBase64String(image) }, "text/plain");
}
Well,If you go with getting filename only in any browser then you should write
Path.GetFileName(e.fileName);
It will return filename only in any browser
Thanks
Instead of check whether the file has a path or not, what you can do is to just use
GetFileName(path);method
In my c# application, when i upload a file , it needs to be converted to temp file and store in a temporary folder then read the temp file as image find its height width every thing and later stores in databse.I am getting error when I read the temp file as image, as Out of Memory, below is my entire code.
string img = System.Windows.Forms.Application.StartupPath +#"\"+ path;
//in path .png file is accessed.
string filename = Path.GetFileName(img);
string internetCache = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
string IEPath=internetCache+#"\tmp";
if (!Directory.Exists(IEPath))
Directory.CreateDirectory(IEPath);
FileInfo fi = new FileInfo(img);
FileStream fs = fi.OpenRead();
//lResult = URLDownloadToFile(0, img.src, TempFolder & strFileName, 0, 0)
Stream stream = fs;
byte[] buffer = new byte[fs.Length];
stream.Seek(273, SeekOrigin.Begin);
stream.Read(buffer, 0, (int)buffer.Length);
string tempfile = Path.Combine(IEPath, Math.Abs(filename.GetHashCode()) + ".tmp");
File.WriteAllBytes(tempfile, buffer);
fs.Close();
stream.Close();
string _contentType = "application/octet-stream";
FileType Type = FileType.png;
string MimeType = "image/png";
FileStream fst = new FileStream(tempfile, FileMode.Open);
Image _image = System.Drawing.Image.FromStream(fst, true, true);
The last line where I am getting the exception as out of memory.
Please help me to find a solution.
I'd venture that the stream you are reading is corrupted (perhaps because you remove the leading 273 bytes).
I just followed the instructions of the question:
read some file
Copy the file to a temp file
Read as image
Get width & height
var bytes = File.ReadAllBytes(#"C:\temp\duck.jpg");
var temp = Path.GetTempFileName();
File.WriteAllBytes(temp, bytes);
var img = Image.FromFile(temp);
Console.WriteLine ("width: {0}, height: {0}", img.Width, img.Height);