I am new to C# and want to get list of file names in ftp directory. But i read some answer on other topics WebRequestMethods is for the single request.
Here is my current code getting FTP object for a specific files.
I want all files ends with ".txt" and want regex like "*.txt". How can I get all file names
in FTP directory?
reqFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri("ftp://95.0.181.84/bankToCompany/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(obj.ftpUserName,obj.ftpPassword);
System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
FileStream outputStream = new FileStream(obj.collectionFileDownloadAddress + renameAddress, FileMode.Create);
StreamReader reader = new StreamReader(responseStream);
string contents = reader.ReadToEnd();
How to: List Directory Contents with FTP
FTP is an old and horrible protocol to work with even in .Net but MSDN has some documentaion about it here.
Check out the "How to: Download Files with FTP" and "How to: Upload Files with FTP" links to the left aswell if you need.
Related
This question already has an answer here:
Archive or image is corrupted after uploading to FTP and downloading back with FtpWebRequest
(1 answer)
Closed 4 years ago.
Here is my code.
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("path");
ftpRequest.Credentials = new NetworkCredential("log", "pass");
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
byte[] fileContent; //in this array you'll store the file's content
using (StreamReader sr = new StreamReader(#"pathToFile")) //'myFile.txt' is the file we want to upload
{
fileContent = Encoding.UTF8.GetBytes(sr.ReadToEnd()); //getting the file's content, already transformed into a byte array
}
using (Stream sw = ftpRequest.GetRequestStream())
{
sw.Write(fileContent, 0, fileContent.Length); //sending the content to the FTP Server
}
.txt files upload correctly with content but .pdf file not. Have no idea where problem is.
Why do you want to reinvent the upload file FTP while there is already WebClient implemented by Microsoft?
"STOR" means this is a upload in FTP
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("log", "pass");
client.UploadFile("your_server", "STOR", filePath);
}
I'm trying to get into C# programming, but for some reason I'm stuck with trying to count all files that are uploaded on my ftp server. I already tried some code from stackoverflow
Code:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(server);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(user, password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string names = reader.ReadToEnd();
reader.Close();
response.Close();
return names.Split(
new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
He does connect to the server but just shows me there in only one file that he could find.
Here you can see the list as a string:
There is the file which he found:
All files that are uploaded on my server:
Here is my list (I don't understand why there are so many indexes):
Your code works for me, but #Ozug can be right that your server fails to use CRLF line endings.
A more robust (and more efficient too) implementation is:
List<string> names = new List<string>();
while (!reader.EndOfStream)
{
names.Add(reader.ReadLine());
}
It should handle even CR line endings.
See also C# class to parse WebRequestMethods.Ftp.ListDirectoryDetails FTP response.
we currently have a *.BAT file that contains some FTP commands to download a file from our AS400 and save into a TEXT file. The BAT works fine and the text file will show the records inside the downloaded file one under the other.
Now, we wanted to get rid of this *.BAT file and use C# to download the file for us and save into a text file. The problem now is that the file we get contains all the records in ONE single line of string! they are no longer listed under each other.
here is the code we are using:
tpWebRequest request = default(FtpWebRequest);
FtpWebResponse response = default(FtpWebResponse);
StreamWriter writer = default(StreamWriter);
request = WebRequest.Create("*******URL******") as FtpWebRequest;
request.Credentials = new NetworkCredential("user", "pass");
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.UseBinary = true;
response = request.GetResponse() as FtpWebResponse;
writer = new StreamWriter(Server.MapPath("/filename.txt"));
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(37))) //37 for IBM encoding
{
writer.WriteLine(reader.ReadToEnd());
}
writer.Close();
response.Close();
Any idea why we are getting this? and why the simple DOS FTP command work better than our code?
Thanks a lot! :)
ASCII mode will add record delimiters when downloading a physical file. It is the default transfer mode of most ftp clients.
request.UseBinary = false;
Specifying false causes the FtpWebRequest to send a "Type A" command to the server.
Data Transfer Methods
Transferring QSYS.LIB files
The problem might be simple: you read the whole document at once. You need to read every line seperately:
using(StreamReader sr = new StreamReader(fs))
{
while(!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
This question already has answers here:
Upload file and download file from FTP
(3 answers)
Closed 4 years ago.
i need to change the logic in an old system and im trying to get the downloading file to work, any ideas? i need to download the files using ftp in c# this is the code i found but i need to get that into a file instead of a stream
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://192.168.1.52/Odt/"+fileName+".dat");
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
reader.Close();
response.Close();
The suggestion from commenter Ron Beyer isn't bad, but because it involves decoding and re-encoding the text, there is a risk of data loss.
You can download the file verbatim by simply copying the request response stream to a file directly. That would look something like this:
// Some file name, initialized however you like
string fileName = ...;
using (Stream responseStream = response.GetResponseStream())
using (Stream fileStream = File.OpenWrite(filename))
{
responseStream.CopyTo(fileStream);
}
Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
response.Close();
I have code that allows me to access a server to do ftp transactions. I have tested the connection and it works. the problem is saving files. to help paint a picture this is how the address are set up.
ftp server: ftp.MyMainDomain.com
path login ftp points to: www.another_website_Under_myDomain.com/gallery/images
when I tested connection, ftp server tacks me directly to images folder and I have even read the subdirectories out (ie ..images/subdirectory1, ..images/subdirectory2).
What I need now it to be able to save files into each of the folders. I thought that all I had to do was add subdir that I wanted to access to the end of the ftp_server uri but that doesn't work. What should I do?
Uri ftpUri = new Uri((Ftp_Server_Address + "/" + SubDirectory+ "/"), UriKind.Absolute);
if (ftpUri.Scheme == Uri.UriSchemeFtp)// check ftp address,
{
DirRequest = (FtpWebRequest)FtpWebRequest.Create(ftpUri);
DirRequest.Method = ReqMethod;
DirRequest.Credentials = new NetworkCredential(FtpUserName, FtpPassword);
DirRequest.UsePassive = true;
DirRequest.UseBinary = true;
DirRequest.KeepAlive = false;
//change picture to stream
Stream PicAsStream = Pic.Bitmap_to_Stream(Pic.BitmapImage_to_Bitmap(Pic.Photo));
//send ftp with picture
Stream ftpReqStream = DirRequest.GetRequestStream();
ftpReqStream = PicAsStream;
ftpReqStream.Close();
SendFtpRequest(ReqMethod);
}
In this line:
ftpReqStream = PicAsStream;
You are not sending the Stream to ftp Server but you are assigning PicAsStream to ftpReqStream and then closing it. Your code does nothing.
Do it like this:
Create a buffer of your image file (not a stream):
FileStream ImageFileStream = File.OpenRead(your_file_path_Here);
byte[] ImageBuffer = new byte[ImageFileStream.Length];
ImageFileStream.Read(ImageBuffer, 0, ImageBuffer.Length);
ImageFileStream.Close();
and then simply write it to your ftpReqStream:
Stream ftpReqStream = DirRequest.GetRequestStream();
ftpReqStream.Write(ImageBuffer, 0, ImageBuffer.Length);
ftpReqStream.Close();