Upload and rename multiple files to FTP using asp.net - c#

We are creating CMS, in which we want to have the option to upload multiple files to FTP server. The steps are
Open FTP connection
Click browse - Select multiple files - Click upload to FTP
Create a folder on the FTP server
Rename the selected files and upload them to the folder
Close the connection
It will be good if it shows the status of the upload.
We are using asp.net with C#. Any sample code will help. Is there any good components available. I can spend max of $150 to buy a component.
Please help. Thanks in advance.

First of all, you should use an open source CMS and improve the code to your needs, don't try to reinvent the wheel!
Second, there is no need to spend money, plenty of solutions out there ...
you can use, for example Uploadify to pass user files to your server, then using any FTP Example upload the files to the FTP and delete them from the server upon success.
if you don't want to have the "middle men", just upload directly to the FTP
string name = Path.GetFileName(UploadControl.FileName);
byte[] data = UploadControl.FileBytes;
using (WebClient client = new WebClient()) {
client.UploadData("ftp://my.ftp.server.com/myfolder/" + name, data);
}

Related

loading a file from http to a local filepath temporarily using c# webclient

I want to save a file from a http link to the local drive just temporarily in order to access it, this one is working so far and I'm getting the data but a need to write this data to a local file, for example to C:\Windows\temp\test.text, this file should be deleted afterwards.
WebClient client = new WebClient();
string url = "http://www.example.com/test.text";
var file = client.DownloadData(url);
could any one help me on this, thank you!
You cannot write a file on client machine due to security, Any program executing in the browser executes within the browser sandbox and has access to limited features like printer, cookies, etc.
You can write the data to file as a Response object to the client's browser. The Client has the choice of whether to save it or not to his machine.

How to read txt file on Client from aspx c# website

i have a question, I have this code
foreach (string line in File.ReadLines(**#"C:\fis32v6\fis32.ini"**))
{
if (line.Contains("TEST1"))
{
Label1.Text="TEST1";
PdLine = "1";
}
}
DataSet ds;
ds = GetData(PdLine.ToString());
I want to read from txt file on client specific line with condition. When developing this and building the code it works, what ever i change in txt file can be read from my PC. But when I run the website on server it reads the txt file on that server instead of client I opened the website.
Is there any possibility to make the path relative?
As John mentioned that would be a huge security issue, mostly to make sure the website doesn't dig around in your system.
However it can be instigated from client side.
Just have search here on SO for 'upload file using asp.net' there are loads of hits with answers listed.
You didn't mention specific versions you use (MVC?, asp.net? / core?), and no context as to what workflow your code is running in (is it run on connection or during a specific process), is it configuration settings used for the web session itself? but it is possible to upload.
Should you require the file during startup that might be a bit trickier as you'd have to upload it somehow.
If however it is settings for the web session, why not save it in a cookie?

Risks in processing a user-provided CSV file

I upload a .csv file to server using ASP.NET FileUpload control and a button. How can I be sure if it is valid .csv file or not ? I mean hackers can write some scripts inside file or they can convert abc.exe to abc.csv and upload server. In second case, is there any way to execute abc.csv file and if it is, is there any solution to avoid from it?
I will read file and if it is in correct format, such as (name,age,birthplace), I will insert them to database. But hacker can write script like ('get all info','from','database').
I am using SQL Server and C#.
I had lots of research in internet but lots of posts are about images, not csv.
What are the risks of csv file while loading to server? How can I check if file has macro virus or something like that?
I hope I could explain my problem.
Please let me know your opinions.
private void ReadCSVFile(string filepath)
{
receiverList = new List<ReceiverUser>();
try
{
if (filepath == string.Empty)
return;
using (StreamReader sr = new StreamReader(filepath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
SplitLine(line);
}
}
#region row add test
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Mail", typeof(string));
dt.Columns.Add("Amount", typeof(double));
}
DataRow NewRow;
foreach (var item in receiverList)
{
NewRow = dt.NewRow();
NewRow[0] = item.Name + " " + item.Surname;
NewRow[1] = item.Mail;
NewRow[2] = item.Amount;
dt.Rows.Add(NewRow);
}
grdRec.DataSource = dt;
grdRec.DataBind();
#endregion
}
catch (Exception)
{
}
}
I read file using StreamReader. So if one of parameter of csv file includes a macro code, will it be executed directly? All I want is to know it actually.
Every potential vulnerability you expose yourself to when dealing with uploaded files is determined by what you do with the file.
If you can let users upload files, which you store as-is for other users to download, then one user can upload a virus-infected executable that will ruin another user's system.
If you let users upload files to any hosted directory because they can provide a target filename and/or directory, they can upload a file that gets interpreted and/or executed by the web server by issuing a request to the file (.php, .aspx, ...). This way a malicious user can execute their code on your server, doing whatever their evil heart desires.
If you let users upload an image and then resize it through some library, then your server is vulnerable to the exploits that exist in that version of that library. A malicious user can then for example inject executable code in an EXIF tag if some image processor library is known to be vulnerable to that.
If you read a CSV file and want to insert its data into a database, then if you simply concatenate an SQL string using this user input, you're going to have yourself a Bobby Tables.
If you run an uploaded Word file through the Word application itself (with all security turned off), then Word Macros will be executed on your server. You also don't want that.
So it all comes down to user input sanitization.
Now for your actual question: you're reading user input into a DataTable, in order to later insert that into an SQL database. This is just fine, because a DataTable will do the proper sanitization before crafting the SQL. But don't take my word for it: for all we know, the DataTable has an exploit as well.
You can follow the directions in the OWASP security topic about "Unrestricted file uploads" at https://www.owasp.org/index.php/Unrestricted_File_Upload.
In general, the best practice is to store the files with a internal and secure file name and store the real name in a database or another data source, associated to that file (also, it helps when the file name contains characters that are incompatible with the target filesystem).
If you don't need to track the file name of the uploaded file, then you can rename the file after uploading using another secure name.
Some Examples of distinct problems associated with file uploads are
Attacks on application platform
Upload .gif file to be resized - image library flaw exploited
Upload huge files - file space denial of service
Upload file using malicious path or name - overwrite a critical file
Upload file containing personal data - other users access it
Upload file containing "tags" - tags get executed as part of being
"included" in a web page
Upload .rar file to be scanned by antivirus - command executed on a
server running the vulnerable antivirus software
Attacks on other systems
Upload .exe file into web tree - victims download trojaned executable
Upload virus infected file - victims' machines infected
Upload .html file containing script - victim experiences Cross-site
Scripting XSS)
Upload .jpg file containing a Flash object - victim experiences
Cross-site Content Hijacking.
Upload .rar file to be scanned by antivirus - command executed on a
client running the vulnerable antivirus software

Get last modified date of a remote file

I have an app with which at startup it downloads a file from a remote location (through the net) and parses it's contents.
I am trying to speed up the process of startup as the bigger the file gets the slower the app starts.
As a way to speed up the process I thought of getting the last modified date of the file and if it is newer from the file on the user's pc then and only then download it.
I have found many ways to do it online but none of them are in C# (for windows store apps). Does anybody here know of a way of doing this without the need to download the file? If I am to download the file then the process is sped up at all.
My C# code for downloading the file currently is this
const string fileLocation = "link to dropbox";
var uri = new Uri(fileLocation);
var downloader = new BackgroundDownloader();
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("feedlist.txt",CreationCollisionOption.ReplaceExisting);
DownloadOperation download = downloader.CreateDownload(uri, file);
await download.StartAsync();
If it helps the file is stored in dropbox but if any of you guys have a suggestion for another free file hosting service I am open to suggestions
Generally, you can check the file time by sending HEAD request and parsing/looking HTTP header response for a Last-Modified filed. The remote server should support it and DropBox does not support this feature for direct links (only via API). But DropBox have another feature, the headers have the etag field. You should store it and check in the next request. If it changed - the file has been changed too. You can use this tool to check the remote file headers.

FTP transfer via ASP.net page

I'm rather new to development and I have a problem which I haven't sound a solution for. I can't seem to find if it is possible or not to solve, anyway..
I want to create an asp page which would allow a user to download a whole folder from an ftp server. The ftp server itself is not on the same physical server as the asp site. To further complicate the issue is that I want to use either explicit or implicit transfer which I can't seem to work in a browser.
The webpage acts as an intermediary between the client and the ftp server, and is meant to be as user friendly as possible. eg. the user just have to press download and it automatically downloads from the ftp server without the use of an installed local client.
client -> asp page -> ftp server
client <- ftp server
My problem is that the asp page does not have the permission to create files on the client system. I have managed to connect to the ftp and try to download all files in a folder but the files do not appear on the client in the target folder.
I might just be searching for the wrong terms but I would appreciate any feedback.
when you say "client" I assume you are referring to the asp.net server. In that case you need to check what user the app pool for your website is running under. Then you need to make sure that user has write permissions to the folder you are storing the ftp files in.
The user is most likely network service.
Your ASP site will not be able to write directly to the end user's system. Just think, would you want any website to have direct access to your file system?
You could download the files to a temporary folder on the Web Server, and then use write it in a response to prompt the user to download it.
Here is a SO question regarding downloading files in ASP.NET
From our question's comment discussion, looks like you are looking to provide user with a option to download file which you have collected on server side from ftp server
//Connect to your file
FileStream sourceFile = new FileStream(Server.MapPath(#"FileName"), FileMode.Open);
float FileSize= sourceFile.Length;
//Write the file content to a byte Array
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
//Build HTTP Response object
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Length", getContent.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.BinaryWrite(getContent);
Response.Flush();
Response.End();
Please see if the above code helps.
Also, check out HTTP Response file Attachment Discussion

Categories