C# single file FTP download - c#

I am trying to download a file usng FTP within a C# console application, but even though I now the paths are correct I always get an error saying "550 file not found".
Is there any way, to return the current path (once connected to the server)?
// lade datei von FTP server
string ftpfullpath = "ftp://" + Properties.Settings.Default.FTP_Server + Properties.Settings.Default.FTP_Pfad + "/" + Properties.Settings.Default.FTP_Dateiname;
Console.WriteLine("Starte Download von: " + ftpfullpath);
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential(Properties.Settings.Default.FTP_User, Properties.Settings.Default.FTP_Passwort);
byte[] fileData = request.DownloadData(ftpfullpath);
using (FileStream file = File.Create(#path + "/tmp/" + Properties.Settings.Default.FTP_Dateiname))
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
Console.WriteLine("Download abgeschlossen!");
}
EDIT
My mistake. Fixed the filepath, still getting the same error. But if I connect with FileZilla that's the exact file path.

Finally found a solution by using System.Net.FtpClient (https://netftp.codeplex.com/releases/view/95632) and using the following code.
// aktueller pfad
string apppath = Directory.GetCurrentDirectory();
Console.WriteLine("Bereite Download von FTP Server vor!");
using (var ftpClient = new FtpClient())
{
ftpClient.Host = Properties.Settings.Default.FTP_Server;
ftpClient.Credentials = new NetworkCredential(Properties.Settings.Default.FTP_User, Properties.Settings.Default.FTP_Passwort);
var destinationDirectory = apppath + "\\Input";
ftpClient.Connect();
var destinationPath = string.Format(#"{0}\{1}", destinationDirectory, Properties.Settings.Default.FTP_Dateiname);
Console.WriteLine("Starte Download von " + Properties.Settings.Default.FTP_Dateiname + " nach " + destinationPath);
using (var ftpStream = ftpClient.OpenRead(Properties.Settings.Default.FTP_Pfad + "/" + Properties.Settings.Default.FTP_Dateiname))
using (var fileStream = File.Create(destinationPath , (int)ftpStream.Length))
{
var buffer = new byte[8 * 1024];
int count;
while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, count);
}
}
}

I think your filename is wrong. Your first line writes a different name than what you set to ftpfullpath. You us FTP_Dateiname on the first line but FTP_Pfad when you set ftpfullpath.
To see what's actually happening move your first line after 'string ftpfullpath...')
and change it to Console.WriteLine("Starte Download von: " + ftpfullpath);

Related

Download zip file to big(400 MB) in MVC

The following code works well with small files, like 100MB, but it throws a System.OutOfMemoryException for bigger files, like 400MB. I'm using the NotNetZip as dll to get file as zip.
This is my code:
string pathGetDoc = pathDocs + "\\" + informe.NickName + "\\" + getMesActual() + "\\" + informe.Name;
string fileName = informe.Name;
System.Net.WebClient wc = new System.Net.WebClient();
wc.OpenRead(pathGetDoc);
int bytes_total = Convert.ToInt32(wc.ResponseHeaders["Content-Length"].ToString());
if(bytes_total >= 100000000)
{
using (ZipFile zip = new ZipFile())
{
zip.AddFile(pathGetDoc, fileName);
zip.CompressionMethod = CompressionMethod.BZip2;
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
using (MemoryStream memoryStream = new MemoryStream())
{
zip.Save(memoryStream);
return File(memoryStream.ToArray(), "application/zip", "z.zip");
}
}
}
As you can see, I have a IF to check the size of the file, this work good but when the process goes to save .zip file, I have the error System.OutOfMemoryException

C# How to get file/ copy file from a bzip2 (.bz2) file without extracting the file

I have a .bz2 compressed file, and i want to copy the inside file to another location, without decompressing it.
I use .net 4.5 with C#.
i tried like this, but this is for zip files (.zip):
using (var zip = ZipFile.Read(_targetPathComplete + "\\" + file[0].ToUpper() + "_" + file[1].ToUpper() + ".bz2"))
{
Stream s = zip[file[0].ToUpper() + "_" + file[1].ToUpper()].OpenReader();
// fiddle with stream here
using (var fileStream = File.Create(_targetPathComplete + "\\" + file[0].ToUpper() + "_" + file[1].ToUpper() + ".HDC"))
{
s.Seek(0, SeekOrigin.Begin);
s.CopyTo(fileStream);
}
}
Or compress a file with bzip2 algorithm and give an extension .HDC to it.
I think i solved it like this, at least the file i have wit this method is the same as when i copy the file from winrar.
var fname = _targetPathComplete + "\\" + file[0].ToUpper() + "_" + file[1].ToUpper() + ".bz2";
using (var fs = File.OpenRead(fname))
{
using (var decompressor = new Ionic.BZip2.BZip2InputStream(fs))
{
var outFname = _targetPathComplete + "\\" + file[0].ToUpper() + "_" + file[1].ToUpper() + ".HDC";
using (var output = File.Create(outFname))
{
var buffer = new byte[2048];
int n;
while ((n = decompressor.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, n);
}
}
}
}

How to upload a file and save it in an specific folder in local computer?

I want to take (upload) a file to a specific folder that I have created in my project (on local computer not a server!).
Here is the code that I am using:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("images/" + filename));
I have added the Fileupload, and the code above in a button. But the code won't work. What's the problem?
I also used this form:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("~DesktopModules/UshtrimiDyte/images/" + filename));
I also used it with double back slashes, but that didn't work either. How can I solve my problem?
Try the above
string path = Server.MapPath("~DesktopModules/UshtrimiDyte/images/" + filename);
System.IO.Stream myStream;
Int32 fileLen;
byte[] Input = null;
fileLen = FileUpload1.PostedFile.ContentLength;
if (fileLen > 0)
{
Input = new Byte[fileLen];
myStream = FileUpload1.FileContent;
myStream.Read(Input, 0, fileLen);
string I_Docx_type = FileUploadFieldDoc.FileName.Substring(FileUpload1.FileName.LastIndexOf(".") + 1);
WriteToFile(path + "." +I_Docx_type, ref Input);
path += "." + I_Docx_type;
}
method
private void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file
System.IO.FileStream newFile = new System.IO.FileStream(strPath, System.IO.FileMode.Create);
// Write data to the file
newFile.Write(Buffer, 0, Buffer.Length);
// Close file
newFile.Close();
}

How to send XML file from smart device to PC in C#?

I'm developing a web application for a handheld RFID reader (windows CE),
and I'm trying to send an XML file from the RFID reader to a laptop throgh wireless network or GPRS. The code works properly with "windows form application" on MS visual studio, but when I try to use it with "smart device application" it doesn't work... an error appears for the "ReadAllBytes" method:
System.IO.File dose not contain a definition for ReadAllBytes
Please help me to handle this error.
Thanks.
The code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string IpAddressString = "10.1.1.104";
IPEndPoint ipEnd_client = new
IPEndPoint(IPAddress.Parse(IpAddressString), 5656);
Socket clientSock_client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
string fileName = "student.XML";
string filePath =#"My Device\";
fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.UTF8.GetBytes(fileName);
if (fileNameByte.Length > 5000 * 1024)
{
curMsg_client = "File size is more than 5Mb,
please try with small file.";
MessageBox.Show("File size is more than 5Mb,
please try with small file.");
return;
}
MessageBox.Show("Buffering ...");
string fullPath = filePath + fileName;
byte[] fileData =File.ReadAllBytes(fullPath);
byte[] clientData = new byte[4 + fileNameByte.Length +
fileData.Length];
//byte[] clientData = new byte[4 + fileNameByte.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
MessageBox.Show("Connection to server ...");
clientSock_client.Connect(ipEnd_client);
MessageBox.Show("File sending...");
clientSock_client.Send(clientData, 0, clientData.Length, 0);
MessageBox.Show("Disconnecting...");
clientSock_client.Close();
MessageBox.Show ("File [" + fullPath + "] transferred.");
}
catch (Exception ex)
{
if (ex.Message == "No connection could be made
because the target machine actively refused it")
{
MessageBox.Show ("File Sending fail. Because
server not running.");
}
else
{
MessageBox.Show ("File Sending fail." +
ex.Message.ToString());
}
}
}
It's because, as the error states, ReadAllBytes doesn't exist in the Compact Framework. You have to use an overload of Read to get the data.
Something along these lines:
using (var reader = File.OpenRead(filePath))
{
var fileData = new byte[reader.Length];
reader.Read(fileData, 0, fileData.Length);
}

"500 error" in ASP.NET file-upload page?

I am calling this PHP code from Android to transfer file from Android to server and its working perfectly fine.
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
But my server application is in .net and I have to write this code in .net
I tried to write .net version code but it does not work and returns 500 internal server error.
public partial class uploadfiles : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
HttpFileCollection uploadFile = Request.Files;
if (uploadFile.Count > 0)
{
HttpPostedFile postedFile = uploadFile[0];
System.IO.Stream inStream = postedFile.InputStream;
byte[] fileData = new byte[postedFile.ContentLength];
inStream.Read(fileData, 0, postedFile.ContentLength);
postedFile.SaveAs(Server.MapPath("Data") + "\\" + postedFile.FileName);
}
}
catch (Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Message : " +ex.Message);
sb.AppendLine("Source : " + ex.Source);
sb.AppendLine("StackTrace : " + ex.StackTrace);
sb.AppendLine("InnerException : " + ex.InnerException);
sb.AppendLine("ToString : " + ex.ToString());
LogInToFile(sb.ToString());
}
}
}
It does not log any exception or even I think it does not reach to its first line. I checked it through Log file. as it does not work. please help.
Android code is below
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/data/file_to_send.mp3";
String urlServer = "http://192.168.1.1/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}
The default max file size limit in ASP.NET application is 4 MB. You can configure the application to accept bigger size by setting the below in web.config
<system.web>
<httpRuntime maxRequestLength="20480" />
</system.web>
To learn more about configuring the file size limit check out Large file uploads in ASP.NET
Try this:
postedFile.SaveAs(Server.MapPath("~/Data/" + postedFile.FileName ));
where ~/Data/ is the location where you want to save your file.
then + postedFile.FileName your filename.
Best Regards

Categories

Resources