File handling in c# - c#

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);

Related

How to get size of zip file before save to disk by using Ionic.Zip.ZipFile?

I am usig Ionic.Zip.ZipFile.I want to create 10 mb zip file.I need get size of ZipFile before save to disk.Is it possible ?
private static string tempPath = "#Temp Folder";
List<string> fileNames = new List<string>();
using (Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile())
{
for (int i = 0; i < fileNames.Count; i++)
{
zf.AddFile(tempPath + fileNames[i], string.Empty);
//How can I get size of zf before save here ?
if(zf size==10mb)
{
zf.Save(tempPath + string.Format("{0}-{1}-{2}.zip","XXX", "XXX",
DateTime.Now.ToString("yyyyMMdd")));
}
}
}
You can save your zip into a MemoryStream:
var ms = new MemoryStream();
zip.Save(ms);
then read the MemoryStream.Length Property and get the size.
If you then still want to save it to disk just use the memory stream you already have:
FileStream file = new FileStream("file.zip", FileMode.Create, FileAccess.Write);
// I believe you'll need to rewind the stream before saving
ms.Seek(0, SeekOrigin.Begin);
ms.WriteTo(file);
file.Close();
ms.Close();

How to create and save ics file using save dialog box?

I am working on the schedule control. i need to export the schedule appointments.
from the below code i have created the Test.ics file in temp folder and then copied to new location.
how to do save the file without save temporarily in the temp folder.
Is it possible to store the file in buffer or any temp object instead of storing it in the temp folder?
please find my code snippet below...
string fileName = "Test.ics";
InternetCalendaring.ICSBuilder icsbBuilder = new InternetCalendaring.ICSBuilder(vecVEvents);
sRes = icsbBuilder.ICSBuildProcess();
string FilePath = System.IO.Path.GetTempPath() + fileName;
System.IO.File.WriteAllText(FilePath, sRes);
FileStream MyFileStream = new FileStream(FilePath, FileMode.Open);
long FileSize;
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
System.Web.HttpContext.Current.Response.AddHeader("content-type", "text/Calendar");
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
System.Web.HttpContext.Current.Response.BinaryWrite(Buffer);
System.Web.HttpContext.Current.Response.Clear();
HttpContext.Current.Response.End();
Thanks in advance...
string fileName = "Test.ics";
InternetCalendaring.ICSBuilder icsbBuilder = new InternetCalendaring.ICSBuilder(vecVEvents);
sRes = icsbBuilder.ICSBuildProcess();
byte[] Buffer = Encoding.Unicode.GetBytes(sRes);
System.Web.HttpContext.Current.Response.AddHeader("content-type", "text/Calendar");
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
System.Web.HttpContext.Current.Response.BinaryWrite(Buffer);
//System.Web.HttpContext.Current.Response.Clear();
HttpContext.Current.Response.End();

Save an image on asp.net server

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.
}

How to read a text file path after extracting the zip file from FTP

1) I am having a problem in reading a text file from my given path .
2) When i download the zip file from ftp i extracted it my extracting is working fine ,
3) The problem is when i download the file from ftp the file which i download is zip file i extract it to a text file and delete the zip file after extracting it and when i
try to read text file from the given path, the path reads the zip file not a text file
4) the code i am using for FTP and extracting the zipfile is,
private void DownloadMonth(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + ftpMonth + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = true;
reqFTP.UsePassive = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long c1 = response.ContentLength;
int bufferSize = 2048000;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
string Path1 = (string)(Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_" + "\\" + fileName);
DirectoryInfo di = new DirectoryInfo(Path1);
FileInfo fi = new FileInfo(Path1);
Decompress(fi);
File.Delete(Path1);
}
catch (Exception ex)
{
}
}
Decompress Code
public static void Decompress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Get original file extension, for example "doc" from report.doc.gz.
string curFile = fi.FullName;
string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
//Create the decompressed file.
//using (FileStream outFile = File.Create(fi.FullName + ""))
//using (FileStream outFile = File.Create(System.Text.RegularExpressions.Regex.Replace(fi.FullName, ".txt$", "") + ""))
using (FileStream outFile = File.Create(origName + ".txt"))
{
using (GZipStream Decompress = new GZipStream(inFile,
CompressionMode.Decompress))
{
//Copy the decompression stream into the output file.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
{
outFile.Write(buffer, 0, numRead);
}
Console.WriteLine("Decompressed: {0}", fi.Name);
}
}
}
}
The code i use to download the text file from FTP and read the text file is
private void button1_Click(object sender, EventArgs e)
{
this.DownloadMonth(a, name_Month);
string Path1 = (string)(Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_" + "\\" + name_Month);
StreamReader reader1 = File.OpenText(Path1);
string str = reader1.ReadToEnd();
reader1.Close();
reader1.Dispose();
}
There would be a great appreciation if someone can solve my problem.
Thanks In Advance
It looks like you're trying to read the binary file from your button1_Click method, instead of the text file. That's just a matter of giving it the wrong filename. You could try just using:
string Path1 = Application.StartupPath + "\\TEMP\\TEMP_BACKFILL_\\"
+ name_Month + ".txt";
(in button1_Click)
... but really you should be able to diagnose what's going wrong yourself:
Is the file being downloaded correctly?
Is the decompression working?
Does the text file look okay afterwards (on the file system)?
If everything's working up to that point, then the download and decompression code is irrelevant, and it's obviously just the reading part in the click handler which is failing. If the text file isn't being created properly, then obviously something is wrong earlier in the process.
It's important to be able to diagnose this sort of thing yourself - you've got a clear 3-step process, and the results of that process should be easy to find just by looking on the file system, so the first thing to do is work out which bit is failing, and only look closely at that.
As an aside, in various places you're manually calling Close on things like streams and readers. Don't do that - use a using statement instead. You should also look at File.ReadAllText as a simpler alternative for reading the whole of a text file.
try string Path1 = origName + ".txt" in button click

how to compress and uncompress a text file

I am having two problems
My problems are
My file name is 20110505.txt , and it is compressing a zip file name as -> 20110505.txt.zip
But I need after compressing this file 20110505.txt as --> 20110505.zip only.
I am using this dll
using System.IO.Compression;
Here is my code for compress,
1)is my text format
string path = DayDestination + "\\" + txtSelectedDate.Text + ".txt";
StreamWriter Strwriter = new StreamWriter(path);
DirectoryInfo di = new DirectoryInfo(path);
FileInfo fi = new FileInfo(path);
Compress(fi);
public static void Compress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Prevent compressing hidden and already compressed files.
if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
!= FileAttributes.Hidden & fi.Name != ".zip")
{
// Create the compressed file.
using (FileStream outFile = File.Create(fi.FullName + ".zip"))
//using (FileStream outFile = File.Create( fi.Name+ ".zip"))
{
using (GZipStream Compress = new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into the compression stream.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
Compress.Write(buffer, 0, numRead);
}
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
}
If my zip file name is 20110505.zip after uncompressing i want my file name to be 20110505.txt . after uncomressing the zip file to text file i want to delete the zip file after compressing
string Path2 = (string)(Application.StartupPath + "\\TEMP\\" + "\\" + name_atoz);
DirectoryInfo di = new DirectoryInfo(Path2);
FileInfo fi = new FileInfo(Path2);
Compress(fi);
public static void Decompress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Get original file extension, for example "doc" from report.doc.gz.
string curFile = fi.FullName;
string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
//Create the decompressed file.
using (FileStream outFile = File.Create(origName))
{
using (GZipStream Decompress = new GZipStream(inFile,
CompressionMode.Decompress))
{
//Copy the decompression stream into the output file.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
{
outFile.Write(buffer, 0, numRead);
}
Console.WriteLine("Decompressed: {0}", fi.Name);
}
}
}
}
I want this because i am creating a project which reads the text file .
Is there any suggestion for my problem.
Thanks In Advance
As Mitch pointed out in the comments above, the problem seems to be with your file name being used for the zip file. You include the FullName, but that has the .txt at the end. Trim that off and you should have what you want.
The line I'm talking about is this one:
using (FileStream outFile = File.Create(fi.FullName + ".zip"))
A simple way to fix it would be as follows:
using (FileStream outFile = File.Create(System.Text.RegularExpressions.Regex.Replace(fi.FullName, ".txt$", "") + ".zip"))
To delete your zip file after you decompress it, put the following line in your Decompress method as the very last line (outside your outer-most using statement):
File.Delete(fi);
You probably want to wrap that in a try-catch but this is the basic code to run. Here is an article on how to delete a file safely:
http://www.dotnetperls.com/file-delete

Categories