I want to Upload a file from the Path given which should be a IP Address and search a Excel file there and Upload in to a Database.
The Excel File will have multiple Sheets to be Uploaded.
I also want to store different sheets in to different tables in Database.
How Can I do this in ASP.NET.
If you Are using FTP server Means write like below.The below sample is working fine with out database.
FtpWebRequest
string CompletePath = "C:/Doc/test.xlsx"; //path for file
private FtpWebRequest FTPDetail(string FileName)
{
string uri = "";
string serverIp = "255.255.255.1"; //Ftp server IP address
string Username = "test"; // Ftp User name
string Password = "test123"; // Ftp Password
uri = "ftp://" + serverIp + "/root/" + FileName;
FtpWebRequest objFTP;
objFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
objFTP.Credentials = new NetworkCredential(Username, Password);
objFTP.UsePassive = true;
objFTP.KeepAlive = false;
objFTP.Proxy = null;
objFTP.UseBinary = false;
objFTP.Timeout = 90000;
return objFTP;
}
Upload file
public bool UploadFile()
{
FtpWebRequest objFTP= null;
try
{
objFTP= FTPDetail("File.xlsx");
objFTP.Method = WebRequestMethods.Ftp.UploadFile;
using (FileStream fs = File.OpenRead(CompletePath))
{
byte[] buff = new byte[fs.Length];
using (Stream strm = objFTP.GetRequestStream())
{
contentLen = fs.Read(buff, 0, buff.Length);
while (contentLen != 0)
{
strm.Write(buff, 0, buff.Length);
contentLen = fs.Read(buff, 0, buff.Length);
}
objFTP = null;
}
}
return true;
}
catch (Exception Ex)
{
if (objFTP!= null)
{
objFTP.Abort();
}
throw Ex;
}
}
Related
I use the following code from here to upload large files to ftp site.
As the file is uploaded to the server I go to the server with the RDP and can not open it because it is being used by another process.
My question is, can I set the file sharing mode so that I can read the file while writing? I want to read the uploaded file while it is being written.
FileStream fs = null;
Stream rs = null;
try
{
string file = "D:\\RP-3160-driver.zip";
string uploadFileName = new FileInfo(file).Name;
string uploadUrl = "ftp://ftp.Sitename.com/tempFiles/";
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
requestObj.Credentials = new NetworkCredential("usernam", "password");
rs = requestObj.GetRequestStream();
byte[] buffer = new byte[8092];
int read = 0;
while ((read = fs.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, read);
}
rs.Flush();
}
catch (Exception e)
{
MessageBox.Show("File upload/transfer Failed.\r\nError Message:\r\n" + ex.Message, "Succeeded", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (rs != null)
{
rs.Close();
rs.Dispose();
}
}
Try the following, I added FileShare.ReadWrite to the FileStream:
string file = "D:\\RP-3160-driver.zip";
string uploadFileName = new FileInfo(file).Name;
string uploadUrl = "ftp://ftp.Sitename.com/tempFiles/";
using (FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
requestObj.Method = WebRequestMethods.Ftp.UploadFile;
requestObj.Credentials = new NetworkCredential("usernam", "password");
using (Stream rs = requestObj.GetRequestStream())
{
stream.CopyTo(rs);
}
}
I have a simple FTP uploader (mostly not my own code, still learning)
It works just fine but it is corrupting exe files, from my reading around that is because it's not a binary reader. But what is confusing is that I am telling it to use binary.
This is my code:
private void UploadFileToFTP(string source)
{
String sourcefilepath = textBox5.Text;
String ftpurl = textBox3.Text; // e.g. ftp://serverip/foldername/foldername
String ftpusername = textBox1.Text; // e.g. username
String ftppassword = textBox2.Text; // e.g. password
try
{
string filename = Path.GetFileName(source);
string ftpfullpath = ftpurl + "/" + new FileInfo(filename).Name;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
Stream.Read does not guarantee you to read all bytes you have requested.
Specifically FileStream.Read documentation says:
count: The maximum number of bytes to read.
Return Value: The total number of bytes read into the buffer. This might be less than the number of bytes requested if that number of bytes are not currently available, or zero if the end of the stream is reached.
To read whole file to memory, use File.ReadAllBytes:
byte[] buffer = File.ReadAllBytes(source);
Though you should actually use Stream.CopyTo, to avoid storing huge files completely to memory:
fs.CopyTo(ftp.GetRequestStream());
Not sure what issue you're having.
This code works just fine for me:
String sourcefilepath = "";
String ftpurl = ""; // e.g. ftp://serverip/foldername/foldername
String ftpusername = ""; // e.g. username
String ftppassword = ""; // e.g. password
var filePath = "";
try
{
string filename = Path.GetFileName(sourcefilepath);
string ftpfullpath = ftpurl + "/" + new FileInfo(filename).Name;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
byte[] buffer = File.ReadAllBytes(sourcefilepath);
ftp.ContentLength = buffer.Length;
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}
I wrote below function to upload file to ftp.it's working properly but i need to get uploaded file name.I think ftp server should write file name in response,am i right?
public static string UploadFileToFTP(string source,string destination)
{
string filename = Path.GetFileName(source);
string ftpfullpath = #ConfigurationManager.AppSettings["ftp_url"].ToString();
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath+#destination);
ftp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ftp_user"].ToString(), ConfigurationManager.AppSettings["ftp_pass"].ToString());
string[] jj = ftp.Headers.GetValues(0);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFileWithUniqueName;
FileStream fs = File.OpenRead(#source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
return ConfigurationManager.AppSettings["ftp_http_url"].ToString() + #destination + "/" + response.ToString();//response.?
}
You just need to read the Response stream
string fileName = new StreamReader(response.GetResponseStream()).ReadToEnd();
Or better
string fileName;
using(s = new StreamReader(response.GetResponseStream())) {
fileName = s.ReadToEnd();
}
I'm not sure why you're going all "bare" and using FtpWebRequest, this can be resolved with three LOC using WebClient, which returns a byte[] response:
using (WebClient webClient = new WebClient())
{
webClient.Credentials = new NetworkCredential(
ConfigurationManager.AppSettings["ftp_user"].ToString(),
ConfigurationManager.AppSettings["ftp_pass"].ToString());
byte[] response = webClient.UploadFile("ftp://address.toserver.com",
WebRequestMethods.Ftp.UploadFileWithUniqueName,
"PathToLocalFile");
var fileName = Encoding.UTF8.GetString(response);
}
Here is my code to upload a file :
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential("****", "*****");
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
reqFTP.ContentLength = stream.Length;
// reqFTP.EnableSsl = true; // it's FTPES type of ftp
int buffLen = 2048;
byte[] buff = new byte[buffLen];
int contentLen;
try
{
Stream ftpStream = reqFTP.GetRequestStream();
contentLen = stream.Read(buff, 0, buffLen);
while (contentLen != 0)
{
ftpStream.Write(buff, 0, contentLen);
contentLen = stream.Read(buff, 0, buffLen);
}
ftpStream.Flush();
ftpStream.Close();
ftpStream.Dispose();
}
catch (Exception exc)
{
return false;
}
//delete image from local
stream.Flush();
stream.Close();
stream.Dispose();
DeleteFile();
DeleteFile method try to delete the uploaded file; but it has an error that the file is being used by my app and so it can not delete it. Is there any one to help me about this issue?!
UPDATE1 :
private void DeleteFile()
{
DirectoryInfo DirInfo = new DirectoryInfo(#"Direectory Contains uploaded file");
foreach (FileInfo file in DirInfo.GetFiles())
{
file.Delete();
}
}
I assume you want to delete the local file? The error says the file is still in use. Wrap the code where you initalize the stream variable in a using block.
The following code is good for uploading text files, but it fails to upload JPEG files (not completely - the file name is good but the image is corrupted):
private void up(string sourceFile, string targetFile)
{
try
{
string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
//string ftpURI = "";
string filename = "ftp://" + ftpServerIP + "//" + targetFile;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
StreamReader stream = new StreamReader(sourceFile);
Byte[] b = System.Text.Encoding.UTF8.GetBytes(stream.ReadToEnd());
stream.Close();
ftpReq.ContentLength = b.Length;
Stream s = ftpReq.GetRequestStream();
s.Write(b, 0, b.Length);
s.Close();
System.Net.FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
MessageBox.Show(ftpResp.StatusDescription);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I have another solution that can upload a file:
private void Upload(string sourceFile, string targetFile)
{
string ftpUserID;
string ftpPassword;
string ftpServerIP;
ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
FileInfo fileInf = new FileInfo(sourceFile);
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)(FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "//" + targetFile)));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
// Bypass default lan settings
reqFTP.Proxy = null;
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
Byte[] buff;
buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
long filesize = fs.Length;
int i=0;
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
Application.DoEvents();
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
i = i + 1;
//Double percentComp = (i * buffLength) * 100 / filesize;
//ProgressBar1.Value = (int)percentComp;
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}
But here I have the opposite problem - the picture is good, but the file name is corrupted.
I know it is because of the encoding, but I don't know how to make the bytes array have the desired encoding...
Try this bit:
private static void up(string sourceFile, string targetFile)
{
try
{
string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
////string ftpURI = "";
string filename = "ftp://" + ftpServerIP + "//" + targetFile;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
byte[] b = File.ReadAllBytes(sourceFile);
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
MessageBox.Show(ftpResp.StatusDescription);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You should be using a Stream to read binary files, not a StreamReader. StreamReader is designed to read text files only.
In your first code example, enable binary transfer: FtpWebRequest.UseBinary = true. Otherwise it will convert what it thinks are textual line endings between the various platform conventions (but are actually part of the image).
Your second snippet does it the right way. It uses FileStream, not StreamReader. StreamReader is only suitable for text files.
System.Text.Encoding.UTF8.GetBytes(stream.ReadToEnd());
Don't do this unless your stream's contents are text. Change your function to accept a boolean parameter "binary", and use the latter, working method if that flag is set.
If you have this problem: The requested FTP command is not supported when using HTTP
you need set proxy in Null or Nothing.
ftpReq.Proxy = null;
You can see this blog.
http://mycodetrip.com/2008/10/29/fix-for-error-the-requested-ftp-command-is-not-supported-when-using-http-proxy_118/comment-page-1/#comment-2825
Thanks.