FTP file uploaded to ASP page - c#

I have seen some answers similar to my question but still could not figure out.
I am using the code below for a user to upload an MP3 file (I am using FTP) and it worked fine with local host (simple WinForm app) but it threw the error when using remote server (remote DNN site):
System.IO.FileNotFoundException: Could not find file 'C:\Windows\SysWOW64\inetsrv\Test.mp3'.
I know that if the test.mp3 file is in this server location then it should work but it was actually in my C:\Temp\Test.mp3 path. I think the FileUpload1 did not give the correct file path. How can I fix this?
protected void btnUpload_Click(object sender, EventArgs e)
{
string url = System.Configuration.ConfigurationManager.AppSettings["FTPUrl"].ToString();
string username = System.Configuration.ConfigurationManager.AppSettings["FTPUserName"].ToString();
string password = System.Configuration.ConfigurationManager.AppSettings["FTPPassWord"].ToString();
string filePath = FileUpload1.PostedFile.FileName;
if (filePath != String.Empty)
UploadFileToFtp(url, filePath, username, password);
}
public static void UploadFileToFtp(string url, string filePath, string username, string password)
{
var fileName = Path.GetFileName(filePath);
var request = (FtpWebRequest)WebRequest.Create(url + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (var fileStream = File.OpenRead(filePath))
{
using (var requestStream = request.GetRequestStream())
{
fileStream.CopyTo(requestStream);
requestStream.Close();
}
}
var response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload done: {0}", response.StatusDescription);
response.Close();
}

The HttpPostedFile.FileName is a "fully qualified name of the file on the client".
And I believe most web browsers actually provide a file name only, without any path. So you get Test.mp3 only, and when you try to use such "relative" path locally on the server, it gets resolved to a current working directory of the web server, what is the C:\Windows\SysWOW64\inetsrv.
Instead, access an uploaded contents directly using HttpPostedFile.InputStream (copy that to GetRequestStream).
See HttpPostedFile documentation.

Related

Ftp not saving files on server

I am having a strange issue with my ftp class its not sending the file to the server my main code is creating the file ok locally however its not saving it on the server no error is created just completes as if it has transfered it I checked permissions of the user and it is fine.
public void Send(string file)
{
try
{
// read the contents of the file.
byte[] contents = ReadFileContents(file);
var requestUriString = string.Concat(_remoteHost, "/", Path.GetFileName(file));
var request = (FtpWebRequest)WebRequest.Create(requestUriString);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(_remoteUser, _remotePassword);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(contents, 0, contents.Length);
requestStream.Close();
}
}catch(Exception ex)
{
Helper.Log(ex.Message);
}
}
And I checked the request uri is fine. After futher checking .net is reporitng
I have asked the web company to check there server cause it should be there for them even though I cannot see it in filezilla some reason?
This is how my uri looks like
ftp://ftp.mydomain.biz/2018-05-09-14-11.csv
Edit2
The file should go to the root.

How can i use/display a file content uploaded to ipage ftp in my weebly site?

This is the code i'm using to upload a simple text file to my ipage.com ftp:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
namespace ScrollLabelTest
{
class FtpFileUploader
{
static string ftpurl = "ftp://ftp.newsxpressmedia.com";
static string filename = #"c:\temp\test.txt";
static string ftpusername = "newsxpressmediacom";
static string ftppassword = "*****";
static string value;
public static void test()
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
ftpurl + "/" + Path.GetFileName(filename));
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(ftpusername, ftppassword);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#"c:\temp\test.txt");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
catch(Exception err)
{
string t = err.ToString();
}
}
}
}
I see the text file: test.txt on my ipage ftp now. But how can i display on my weebly site the content of the text file i just uploaded ? The ftp in ipage.com is my website domain name ftp account.
I just talked to the help support live chat they told me there is no way to do it.
What i want to do is to upload somehow a text file from my hard drive to my site and display the content of the text file on my site each a minute since the text file is getting update every a minute.
This is what they wrote about the ipage ftp:
You can build your site using Web authoring tools, and then use an FTP program to upload the Web pages to your iPage account.
To access your account using an FTP client, you need to connect to ftp.newsxpressmedia.com with your FTP username and password.
And: newsxpressmedia.com is my website domain on weebly.
I can edit drag and drop and design my site on weebly but how can i display the content of a text file every a minute ?
I know not all but some ftp sites have a "change permissions" setting for each file or folder, if it has that setting then you can change permissions to allow anybody to view the file and just put the direct file location

Copy file from the obtained path to a domain

Hi all is it possible to copy a file from the path obtained to the domain, I tried as follows but I am getting an exception as uri formats are not supported.. So can some one help me how to copy the file
string filePath = "D:\\Folder\\filename.jpg";
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
path = "http://WWW.somedomain.com";
string temppath = path + "/Temp" + "/" + fileInfo.Name;
if (!File.Exists(temppath))
{
var uri = new Uri(temppath);
File.Copy(filePath, uri.AbsoluteUri);
}
You want to check the existence of file on the server. This is not possible using File.Exist method as it doesn't supports the URI. This method expect the relative path and checked the existence on machine (physical location).
In this case you should use WebRequest and get the response from the server. If server returns 404 then your file doesn't exist on the serve or you can check the Content Length.
WebRequest request = WebRequest.Create(new Uri(temppath));
request.Method = "HEAD";
WebResponse response = request.GetResponse()
var contentLength = response.ContentLength;
if (contentLength < 0)
{
// file doesn't exist.
}

C# FTP app uploads to local directory

I've just written a simple FTP console app to upload files on a local server to a remote FTP site. Everything seems to be working fine until it comes to actually transferring the file. For some reason instead of uploading the file to the specified FTP site it stores the entire file locally with no in the Debug folder with no file type and named the same as the ip of the FTP site. I'm thinking that this has something to do with Visual Studio's debugging. Can anybody give me some guidance on this?
Here is the code I'm using to attempt to upload each file in a string array to the FTP site.
private static void Upload(string ftpServer, string userName, string password, string filename)
{
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential(userName, password);
client.UploadFile(ftpServer, "STOR", filename);
}
}
Use this method instead of that one,it worked for me.
//Directory sands for Remote Server Directory ,it must create if dir not exist
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://serverIP/directory/file");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential ("username","password");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
source- http://msdn.microsoft.com/en-us/library/ms229715.aspx
Try this way instead: http://msdn.microsoft.com/en-us/library/ms229715.aspx

FTP Check if file exist when Uploading and if it does rename it in C#

I have a question about Uploading to a FTP with C#.
What I want to do is if the file exists then I want to add like Copy or a 1 after the filename so it doesn't replace the file. Any Ideas?
var request = (FtpWebRequest)WebRequest.Create(""+destination+file);
request.Credentials = new NetworkCredential("", "");
request.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
}
}
It's not particularly elegant as I just threw it together, but I guess this is pretty much what you need?
You just want to keep trying your requests until you get a "ActionNotTakenFileUnavailable", so you know your filename is good, then just upload it.
string destination = "ftp://something.com/";
string file = "test.jpg";
string extention = Path.GetExtension(file);
string fileName = file.Remove(file.Length - extention.Length);
string fileNameCopy = fileName;
int attempt = 1;
while (!CheckFileExists(GetRequest(destination + "//" + fileNameCopy + extention)))
{
fileNameCopy = fileName + " (" + attempt.ToString() + ")";
attempt++;
}
// do your upload, we've got a name that's OK
}
private static FtpWebRequest GetRequest(string uriString)
{
var request = (FtpWebRequest)WebRequest.Create(uriString);
request.Credentials = new NetworkCredential("", "");
request.Method = WebRequestMethods.Ftp.GetFileSize;
return request;
}
private static bool checkFileExists(WebRequest request)
{
try
{
request.GetResponse();
return true;
}
catch
{
return false;
}
}
Edit: Updated so this will work for any type of web request and is a little slimmer.
Since FTP control protocol is slow in nature (send-receive) I suggest first pulling directory content and checking against it before uploading the file. Note that dir can return two different standards: dos and unix
Alternatively you can use the MDTM file command to check if file already exist (used to retrieve timestamp of a file).
There is no shortcut. You need to dir the target directory then use # to determine which name you want to use.
I am working on something similar. My problem was that:
request.Method = WebRequestMethods.Ftp.GetFileSize;
was not really working. Sometimes it gave exception sometimes it didn't. And for the same file! Have no idea why.
I change it as Tedd said (thank you, btw) to
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
and it seems to work now.

Categories

Resources