I am using the code below to upload a file. The files upload without error, but when I open a file with a .docx extension M$ says that the file is corrupted. It is able to repair the file and then open, however. I'd like to fix this so the document opens correctly.
string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = #"C:\" + Guid.NewGuid().ToString() + strExtension;
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
byte[] bytes = new byte[16 * 1024];
int bytesRead;
while ((bytesRead = context.Request.InputStream.Read(bytes, 0, bytes.Length)) > 0)
{
fs.Write(bytes, 0, bytesRead);
}
}
Thanks.
EDITED:
File saves correctly with this code:
while ((bytesRead = context.Request.Files[0].InputStream.Read(bytes, 0, bytes.Length)) > 0)
Also saves correctly with context.Request.Files[0].SaveAs(...);
It looks like you are reading the HttpRequest.InputStream. The better thing to do is check the HttpRequest.Files collection.
(Or even easier, use a FileUpload server control).
Your code is copying the raw input, which is most likely multi-part, to a file.
This doesn't answer your question exactly, but you could use HttpPostedFile.SaveAs to save the content to the desired path.
string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = #"C:\" + Guid.NewGuid().ToString() + strExtension;
context.Request.Files[0].SaveAs(fileName); // i'll ignore the violation of the law of demeter ;)
Related
Hello i want to access my files at resources in Visual Studio but when i Build my .exe file and move it from my Folder i get a message that the files could not be found?
That is my code:
string RunningPath = AppDomain.CurrentDomain.BaseDirectory;
string pdf = string.Format("{0}Resources\\me.pdf", Path.GetFullPath(Path.Combine(RunningPath, #"..\..\")));
Process.Start(pdf);
I tried other methods but it still don't work? :/
Anyone has an idea?
something you could do like this read a file from resource stream
var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("me.pdf");
using (FileStream fs = File.Create(#"c:\temp\me.pdf"))
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, len);
}
};
Process.Start(#"c:\temp\me.pdf");
If you have added the pdf file to Properties.Resources, you can access it as followed.
Call AppDomain.CurrentDomain.BaseDirectory to get bin\Debug folder first.
Then use .. to return to the parent directory
string path = AppDomain.CurrentDomain.BaseDirectory + #"..\..\Resources\test.pdf";
System.Diagnostics.Process.Start(path);
I created a report using ReportViewer and I can generate it on local machine without any problem. On the other hand, I encounter an error "Access to the path 'C:\xxxxxxx.xlsx' is denied." after publishing the application to IIS. Of course it is caused by the permission problem, but in our company, in most cases there is no writing permission to any location of C drive and I think the best approach is to open the generated excel file in memory, etc. (without writing to disk). So, how can I update the method I use in order to achieve this? Any idea?
I send the report (created using ReportViewer) to this method as Stream and I open the generated report without writing to disk:
public static void StreamToProcess(Stream readStream, string fileName, string fileExtension)
{
var myFile = fileName + "_" + Path.GetRandomFileName();
var writeStream = new FileStream(String.Format("{0}\\{1}.{2}",
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), myFile,
fileExtension), FileMode.Create, FileAccess.Write);
const int length = 16384;
var buffer = new Byte[length];
var bytesRead = readStream.Read(buffer, 0, length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, length);
}
readStream.Close();
writeStream.Close();
Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.
InternetCache) + "\\" + myFile + "." + fileExtension);
}
Any help would be appreciated.
Update :
I pass the report stream to this method as shown below:
StreamToProcess(reportStream, "Weekly_Report", "xlsx");
Note : reportStream is the generated report using ReportViewer.
You can write to a MemoryStream instead and return this stream to the caller. Make sure you do not close the instance of your memory stream. You can then pass this memory stream to a StreamWriter instance if you want to process the in-memory file.
public static Stream StreamToProcess(Stream readStream)
{
var myFile = fileName + "_" + Path.GetRandomFileName();
var writeStream = new MemoryStream();
const int length = 16384;
var buffer = new Byte[length];
var bytesRead = readStream.Read(buffer, 0, length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, length);
}
readStream.Close();
return writeStream;
}
Your current approach of calling Process.Start will not work on the IIS server as it will open the Excel document on the server rather than on the users computer. You will have to provide a link to the user to download the file, you could use an AJAX request for this that streams from the MemoryStream. Have a look at this post on further details on how to implement this.
I am using the following piece of code to open a PDF file that I have just created this methods works in one section on my site but it does not seem to redirect to the PDF from another section of my site. What could possible be the reason why the PDF file is not opening.
Context.Response.Buffer = false;
FileStream inStr = null;
byte[] buffer = new byte[1024];
long byteCount;
inStr = File.OpenRead(pdfPath);
while ((byteCount = inStr.Read(buffer, 0, buffer.Length)) > 0) {
if (Context.Response.IsClientConnected) {
Context.Response.ContentType = "application/pdf";
Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
Context.Response.Flush();
}
}
Your pdf path is relative.
You could also read the file in one shot
bytez=File.ReadAllBytes(Server.MapPath(pdfPath))
And send it the same way. Response.BinaryWrite(bytez).
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
I have some files, which are embedded in a resource. How can I save these files on disk via C#?
This should do your job:
string strTempFile = Path.GetTempFileName();
File.WriteAllBytes(strTempFile, Properties.Resources.YourBinaryFileInResource);
Be sure, that the FileType of the included files is set to "binary".
using streams: GetManifestResourceStream gives you a stream to the file in the resource and using a StreamWriter you can write the contents of that stream to disk.
You can get the resource stream, then read from the stream while writing to the file.
byte[] buffer = new byte[1024];
using (Stream output = File.OpenWrite("filename"))
{
using (Stream resourceStream = typeof(Class1).Assembly.GetManifestResourceStream("name of resource"))
{
int bytes = -1;
while ((bytes = resourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytes);
}
}
}
Code is completely untested, just to give you an idea.