Uploading files in dedicated server with asp.net - c#

I upload files and convert it into bytes and saved it in Database. It works correctly in my local system. but I hosted it in dedicated server, it cannot convert path into bytes. It shows an error
'Could not find a part of the path 'C:\fakepath\1003.pdf'.
Code:
//byte[] bContent = myWebClient.DownloadData(#strFileUploadSubSplit[3]);
byte[] bContent = null;
// Open file for reading
System.IO.FileStream _FileStream = new System.IO.FileStream(strFileUploadSubSplit[3].ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read);
// attach filestream to binary reader
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
// get total byte length of the file
long _TotalBytes = new System.IO.FileInfo(strFileUploadSubSplit[3].ToString()).Length;
// read entire file into buffer
bContent = _BinaryReader.ReadBytes((Int32)_TotalBytes);
// close file reader
_FileStream.Close();
_FileStream.Dispose();
_BinaryReader.Close();
string base64String = System.Convert.ToBase64String(bContent, 0, bContent.Length);
str = strFileUploadSubSplit[0] + "*" + strFileUploadSubSplit[1] + "*" + strFileUploadSubSplit[2] + "*" + base64String ;
string URL = "http://dev2.weicorp.com:81/IApp.svc/IApp/Doc";
string ret = string.Empty;
var webRequest = System.Net.WebRequest.Create(URL) as HttpWebRequest;
byte[] byteArray = Encoding.UTF8.GetBytes(str);
webRequest.Method = "POST";
webRequest.ContentType = "application/octet-stream";
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
dataStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
ret = reader.ReadToEnd();
string status = ret.ToString();
context.Response.Write(status);

You have to extract the filename only from the uploaded file:
string file = Path.GetFileName(uploadedFile.FileName);
The fakepath that you are seeing is because for security reasons web browsers do not send the actual path to the uploaded file on the client.

Related

Web service File Stream to Byte[] to FileStream to pdf failing C#

I am trying to create a web service that returns a pdf file as a byte[] and then the app that consumes it grabs the byte[] and saves it as a pdf file and then opens it. The file fails to open at the end.
Here is the Web Service that returns a byte[]
[WebMethod]
public byte[] XXXX(int fileID)
{
try
{
using (EntitiesModel dbContext = new EntitiesModel())
{
string fileFullPath = .....
.......
if (fileFullNamePath != null)
{
FileStream fileStream = new FileStream(fileFullNamePath, FileMode.Open, System.IO.FileAccess.Read);
int len = fileStream.Length.ToInt();
Byte[] documentContents = new byte[len];
fileStream.Read(documentContents, 0, len);
fileStream.Close();
return documentContents;
Then it is called from an app with the following code
string soap = "<?xml version=\"1.0\" encoding=\"utf - 8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<XXXX xmlns=\"http://tempuri.org/\">" +
"<fileID>XXXXX</fileID>" +
"</XXXX>" +
"</soap:Body>" +
"</soap:Envelope>";
string localhostContext = #"http://localhost:3381/";
string webserviceAddress = #"XXXX/XXXX/XXXXX.asmx";
string url = localhostContext + webserviceAddress ;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "text/xml";
request.ContentLength = soap.Length;
request.Timeout = 20000;
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
using (StreamWriter streamWriter = new StreamWriter(stream))
{
streamWriter.Write(soap); }
}
}
byte[] bytes;
try
{
WebResponse response = request.GetResponse();
bytes = ReadFully(response.GetResponseStream());
}
catch (Exception exception)
{
throw;
}
private byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream memoryStream = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Position = 0;
memoryStream.Write(buffer, 0, read);
}
return memoryStream.ToArray();
}
}
FileStream objfilestream =
new FileStream(fileName, FileMode.Create,FileAccess.ReadWrite);
objfilestream.Write(bytes, 0, bytes.Length);
objfilestream.Close();
var process = Process.Start(fileName);
The code runs fine and creates a pdf and then tries to open that pdf. But the file can not be opened. Adobe Acrobat gives the error
Adobe Acrobat Reader could not open XXX.pdf because it is either not a
supported file type or because the file has been damaged (for example, it
was sent as an email attachment and wasn't correctly decoded).
Because I am not getting an error in the code I am at a loss to know where the error is that is not creating the proper file.
There was an issue with the Stream variable called input was not giving length so I used Jon Skeet's suggestion here Stackoverflow:Creating a byte array from a stream
new byte[16*1024];
rather than
new byte[input.length]
There were three things wrong.
memoryStream.Position = 0;
in the while loop was problematic so I removed it.
Secondly when reading the stream. What it returned was the SOAP XMl message with the encoded base64 string in the the XXXXResult XML tag. So I had to extract that.
Finally I had to use
byte[] fileResultBytes = Convert.FromBase64String(resultString);
to get the byte[] from the resultString extracted from the SOAP message. In the test SOAP message, that can be generated locally, it tells you the type of this result string. I missed that initially.
Thanks to VC.One and CodeCaster for their correct suggestions.

ftp upload file corrupted in c# [duplicate]

This question already has an answer here:
Archive or image is corrupted after uploading to FTP and downloading back with FtpWebRequest
(1 answer)
Closed 5 years ago.
hello i have this code to upload image or word file through c# by using ftp.
the code works fine it uploads the file to ftp but file goes corrupted after uploading please advice what is wrong in this thanks
//FTP Server URL.
string ftp = "ftp://ftpip/";
//FTP Folder name. Leave blank if you want to upload to root folder.
string ftpFolder = "folder path to upload";
byte[] fileBytes = null;
//Read the FileName and convert it to Byte array.
string fileName = Path.GetFileName(FileUpload1.FileName);
using (StreamReader fileStream = new StreamReader(FileUpload1.PostedFile.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
try
{
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
//Enter FTP Server credentials.
request.Credentials = new NetworkCredential("ftpuser", "ftppassowrd");
request.ContentLength = fileBytes.Length;
request.UsePassive = true;
request.UseBinary = true;
request.ServicePoint.ConnectionLimit = fileBytes.Length;
request.EnableSsl = false;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileBytes, 0, fileBytes.Length);
requestStream.Close();
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
lblMessage.Text += fileName + " uploaded.<br />";
response.Close();
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
You could use BinaryReader instead of getting the bytes as UTF8 encoding. You should change it;
using (StreamReader fileStream = new StreamReader(FileUpload1.PostedFile.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
to
FileUpload1.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);
using (var binaryReader = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
fileBytes = binaryReader.ReadBytes(FileUpload1.PostedFile.ContentLength);
}

C# - Safe a Base64 as Gif, when the webRequest sends XML?

I sended a WebRequest, and got as Response a String with XML Code within my content.
WebRequest request = WebRequest.Create("...");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
byte[] bytes = Convert.FromBase64String(responseFromServer);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
image.Save("File", System.Drawing.Imaging.ImageFormat.Gif);
The Problem is that "Convert.FromBase64String(responseFromServer)" cant convert to base 64, because the response is:
"<string xmlns="*LINK*"> 'content' </string>"
Can I remove these Tags, or copy out the content?
I hope you got my problem:) Thanks for help and sorry for the bad english x)
you can use XmlDocument..
WebRequest request = WebRequest.Create("...");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
byte[] bytes = Convert.FromBase64String(doc.GetElementsByTagName("string")[0].InnerText);
System.Drawing.Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = System.Drawing.Image.FromStream(ms);
}
I'd recommend using XmlReader for this.
WebRequest request = WebRequest.Create("...");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
//StreamReader reader = new StreamReader(dataStream);
//string responseFromServer = reader.ReadToEnd();
//byte[] bytes = Convert.FromBase64String(responseFromServer);
using (var reader = XmlReader.Create(dataStream))
{
reader.Read();
reader.Read();
string base64 = reader.Value;
byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
image.Save("File", System.Drawing.Imaging.ImageFormat.Gif);
}
}
There is a method for converting from Base64 in the element value directly, but you'd need to know things that more or less require you to read your whole stream anyway to do that (you can look at the edit history to see me working through that ;).

How to download jpg/doc file from my server with Url in asp.net web application

My problem is unable to download file from sever
My code work fine for any Google image-url (eg.:-http://blogs.independent.co.uk/wp-content/uploads/2012/12/google-zip.jpg)
but it is not work in case of my server image-url("eg.:-[http://110.15.445.87/xyz/abc/123.jpg]")
i dont know where is problem
my code is :-
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// The number of bytes read
try
{
String Url = "http://112.196.32.51/ll1/UploadFiles/13062402231250.jpg";
//String Url = "http://blogs.independent.co.uk/wp-content/uploads/2012/12/google-zip.jpg";
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(Url);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
String fileName = "Rock.jpg";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
}

How to download ZipFile From FTP server

I have zip file in ftp server,this zip file contain more then one xml file in it,i want to download this zipfile and save to local disk,i have write below code,i download file but when i try to Extract this zip it throw me error that File is corrupted......
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + file);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
StreamWriter writer = new StreamWriter(destination);
writer.Write(reader.ReadToEnd());
writer.Close();
reader.Close();
response.Close();
You are channeling the result of the FTP request through a StreamReader. This has the usually beneficial effect of handling character encoding, but is not something you ever want to do when dealing with binary data (i.e. a zip file). Instead, you should read the data directly from the stream. Something like:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + file);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// Copy the data from the responseStream to destination 1k at a time (feel free to increase buffer size)
byte[] buffer = new byte[1024];
for (int amountRead = responseStream.Read(buffer, 0, buffer.Length); amountRead > 0; amountRead = responseStream.Read(buffer, 0, buffer.Length))
{
destination.Write(buffer, 0, amountRead);
}
destination.Flush();
response.Close();
Here are sample code for Download file from FTP Server
Uri url = new Uri("ftp://ftp.demo.com/file1.txt");
if (url.Scheme == Uri.UriSchemeFtp)
{
FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url);
//Set credentials if required else comment this Credential code
NetworkCredential objCredential = new NetworkCredential("FTPUserName", "FTPPassword");
objRequest.Credentials = objCredential;
objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
byte[] buffer = new byte[16 * 1024];
int len = 0;
FileStream objFS = new FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
{
objFS.Write(buffer, 0, len);
}
objFS.Close();
objResponse.Close();
}
I think that your problem is the way that you download the zip, here's an article explaining how to use it, i hope it helps:
http://www.vcskicks.com/download-file-ftp.php
Also, there is a question like this here:
how to download compressed file (.zip) through FTP using c#?

Categories