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();
Related
I am trying to display .png / .jpg image in browser but the problem is instead of displaying the image in the browser it is getting downloaded. I have tried using content-disposition:inline as well but its downloading the complete aspx page. Can anyone help me with this. Below is my code
string filePath = "C:\\inetpub\\wwwroot\\Folder\\OSP\\20139000\\";
string filename = "test.jpg";
string contenttype = "image/" +
Path.GetExtension(filename.Replace(".", ""));
FileStream fs = new FileStream(filePath + filename,
FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
////Write the file to response Stream
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contenttype;
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
You miss
Response.Clear();
somewhere at the beginning of the script. Without clearing the response's buffer first, it already contains the text of the *.aspx page the script is run under.
Then, don't set the content's disposition to attachment, completely delete this line.
I have problem with upload image file from Android to remote webservice in asp net c#.
The problem is that the image file sent from Android to the remote server is zero kilobytes; the upload worked, the image file name uploaded is correct in correct folder in the remote server and I don't have error in debug Android and in debug asp net, but this image is empty.
I would greatly appreciate your help.
Thanks in advance
android code in java class:
File mFile = new File("/storage/emulated/0/image_file.jpg");
if(mFile.exists()){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bmp = BitmapFactory.decodeFile(mFile.getAbsolutePath());
bmp.recycle();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Request.addProperty("byteArray", byteArray);
}
WebService in asp net c#
[WebMethod]
public string sendUpload(Byte[] byteArray, string fileName)
{
string Path;
Path = "D:\\Inetpub\\wwwroot\\myAppAndroid\\uploads\\" + fileName;
FileStream objfilestream = new FileStream(Path, FileMode.Create,
FileAccess.ReadWrite);
objfilestream.Close();
return byteArray + "; " + fileName.ToString();
}
First Edit question, I have error in this line
file.Write(byteArray, 0, byteArray.Length);
[WebMethod]
public string sendUpload(Byte[] byteArray, string fileName)
{
string strdocPath;
strdocPath = "D:\\Inetpub\\wwwroot\\myAppAndroid\\uploads\\" + fileName;
System.IO.FileStream file = System.IO.File.Create(HttpContext.Current.Server.MapPath(".\\myAppAndroid\\uploads\\" + fileName));
file.Write(byteArray, 0, byteArray.Length);
file.Close();
return byteArray + "; " + fileName.ToString();
}
you should write the content of the received file on filesystem:
[WebMethod]
public string sendUpload(Byte[] byteArray, string fileName)
{
string Path;
Path = "D:\\Inetpub\\wwwroot\\myAppAndroid\\uploads\\" + fileName;
FileStream objfilestream = new FileStream(Path, FileMode.Create,
FileAccess.ReadWrite);
// here some code is missing
objfilestream.Close();
return byteArray + "; " + fileName.ToString();
}
you have a Byte[] as input that you never write on the server disk.
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);
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
To store the word doc in SQL I have this:
byte[] bytes = new byte[uploader.UploadedFiles[0].InputStream.Length];
var storedFile = new email_attachment();
string strFullPath = uploader.UploadedFiles[0].FileName;
string strFileName = Path.GetFileName(strFullPath);
storedFile.email_attachment_id = Guid.NewGuid();
storedFile.emailer_id = new Guid(dropMailers.SelectedValue);
storedFile.file_name = strFileName;
storedFile.file_data = bytes;
db.email_attachments.InsertOnSubmit(storedFile);
db.SubmitChanges();
To get it back I use this:
var storedFile = db.email_attachments.Where(a => a.email_attachment_id.ToString() == dropAttachments.SelectedValue).Single();
string strPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Storage/Email/Attachments");
File.WriteAllBytes(Path.Combine(strPath, storedFile.file_name), storedFile.file_data.ToArray());
System.IO.FileInfo file = new System.IO.FileInfo(Path.Combine(strPath, storedFile.file_name));
if (file != null && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
//Response.Write("This file does not exist.");
}
Problems: The doc I get back is blank, and I also believe saving it in the file system and then writing it to the response stream isn't very efficient. I'm thinking that step could be skipped. Any help or info would be much appreciated.
Let's look at this code to start with:
byte[] bytes = new byte[uploader.UploadedFiles[0].InputStream.Length];
var storedFile = new email_attachment();
string strFullPath = uploader.UploadedFiles[0].FileName;
string strFileName = Path.GetFileName(strFullPath);
storedFile.email_attachment_id = Guid.NewGuid();
storedFile.emailer_id = new Guid(dropMailers.SelectedValue);
storedFile.file_name = strFileName;
storedFile.file_data = bytes;
db.email_attachments.InsertOnSubmit(storedFile);
db.SubmitChanges();
I can see you creating an empty array - but I can't see where you're populating it anywhere. Shouldn't you be reading from the InputStream instead of just finding out its length?
(You may well want to copy from the input stream into a MemoryStream, and then use ToArray to get a byte array out at the end. There's plenty of sample code around for copying a stream - and in .NET 4 there's even the WriteTo method which makes it easier.)
I haven't even looked at the later code yet - first let's make sure you actually get some data into the database first...
To write to the db:
byte[] bytes = new byte[uploader.UploadedFiles[0].InputStream.Length];
uploader.UploadedFiles[0].InputStream.Read(bytes, 0, bytes.Length);
var storedFile = new document();
string strFullPath = uploader.UploadedFiles[0].FileName;
string strFileName = Path.GetFileName(strFullPath);
storedFile.document_id = Guid.NewGuid();
storedFile.content_type = uploader.UploadedFiles[0].ContentType;
storedFile.original_name = strFileName;
storedFile.file_data = bytes;
storedFile.date_created = DateTime.Now;
db.documents.InsertOnSubmit(storedFile);
db.SubmitChanges();
And to get the document back out:
var storedFile = db.documents.Where(a => a.document_id.ToString() == dropAttachments.SelectedValue).Single();
Response.Clear();
Response.ContentType = "application/x-unknown";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + storedFile.original_name + "\"");
Response.BinaryWrite(storedFile.file_data.ToArray());
Response.End();
Found my answer here: http://imar.spaanjaars.com/414/storing-uploaded-files-in-a-database-or-in-the-file-system-with-aspnet-20#Downloads