I have got the following code, I need to upload multiple files which don't have an extension/type assigned to them. The following code below works, but not on these files as it's trying to make a file for example called: ftp.server/file
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String sourcefilepath = #"path"; // e.g. “d:/test.docx”
String ftpurl = #"ftp"; // e.g. ftp://serverip/foldername/foldername
String ftpusername = #"user"; // e.g. username
String ftppassword = #"pass"; // e.g. password
string[] filePaths = Directory.GetFiles(sourcefilepath);
// Get the object used to communicate with the server.
foreach (string filename in filePaths)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.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(sourcefilepath);
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();
}
}
}
}
The files are from an iPhone backup, iPhone backups don't give the files extensions so I need a work around.
The solution I found was to copy the files and add a dummy extension.
Related
I have no access to Sharepoint server, only like standard user from web page. I can upload manually there my documents. I tried to solve it via C# and I complet any code from examples from net. Our Sharepoint is 2007. My code run without any error. I put there control text to see if its proceed. All runs fine but nothing happens in Sharepoint page, no doc is uploaded. I have no idea why its do nothing :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
namespace Sharepoint
{
class Program
{
public static void CopyStream(Stream read, Stream write)
{
int len; byte[] temp = new byte[1024];
while ((len = read.Read(temp, 0, temp.Length)) > 0)
{
write.Write(temp, 0, len);
/// Console.WriteLine("test");
}
}
static void Main(string[] args)
{
Uri destUri = new Uri("http://gaja/mBreSKCZ/mreports/sales/reportysales/Test_new.txt");
using (FileStream inStream = File.OpenRead(#"C:\Users\TK20382\Test_new.txt"))
{
WebRequest req = WebRequest.Create(destUri);
req.Method = "PUT";
req.Credentials = CredentialCache.DefaultCredentials; // assuming windows Auth
Console.WriteLine("test");
Console.ReadKey();
using (Stream outStream = req.GetRequestStream())
{
CopyStream(inStream, outStream);
}
}
}
}
}
You are missing HttpWebRequest.GetResponse Method which basically invokes PUT request. In addition if you are targeting .NET Framework >=2.0 version, then CopyStream method could be omitted and the line:
CopyStream(inStream, outStream);
replaced with:
inStream.CopyTo(outStream);
Modified version
public static string UploadFile(string targetUrl,ICredentials credentials, string sourcePath)
{
var request = WebRequest.Create(targetUrl);
request.Method = "PUT";
request.Credentials = credentials;
using (var fileStream = File.OpenRead(sourcePath))
using (var requestStream = request.GetRequestStream())
{
fileStream.CopyTo(requestStream);
}
using (var response = request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
Usage
UploadFile("https://contoso.intranet.com/documents/guide.docx", CredentialCache.DefaultCredentials, #"D:\guide.docx");
Alternatively WebClient.UploadFile Method could be utilized as shown below:
public static void UploadFile(string targeUrl, ICredentials credentials, string fileName)
{
using (var client = new WebClient())
{
client.Credentials = credentials;
client.UploadFile(targeUrl, "PUT", fileName);
}
}
This question already has answers here:
Invalid URI: The format of the URI could not be determined
(8 answers)
Closed 6 years ago.
i use this code for ftp upload from this link.
and when i use that, show me that error , what am i doing?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Text;
public partial class CS : System.Web.UI.Page
{
protected void FTPUpload(object sender, EventArgs e)
{
//FTP Server URL.
string ftp = "92.222.117.211";
//FTP Folder name. Leave blank if you want to upload to root folder.
string ftpFolder = "Uploads/";
byte[] fileBytes = null;
//Read the FileName and convert it to Byte array.
string fileName = Path.GetFileName(FileUpload1.FileName);
using (StreamReader fileStream = new StreamReader(FileUpload1.PostedFile.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
try
{
//Create FTP Request.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
//Enter FTP Server credentials.
request.Credentials = new NetworkCredential("foxseria", "244RujnnL2");
request.ContentLength = fileBytes.Length;
request.UsePassive = true;
request.UseBinary = true;
request.ServicePoint.ConnectionLimit = fileBytes.Length;
request.EnableSsl = false;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileBytes, 0, fileBytes.Length);
requestStream.Close();
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
lblMessage.Text += fileName + " uploaded.<br />";
response.Close();
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
}
}
and this is a my code, and the ftp server and username - password are correct.
You are missing the ftp:// prefix, and a slash between the hostname/IP address and the folder name, in your URL.
Your would-be URL is:
92.222.117.211Uploads/filename
While a real URL is like:
ftp://92.222.117.211/Uploads/filename
This is a working code that upload text file to my ftp root. Tested and working.
But now i want to create a sub directory on the root directory and then after creating the directory to upload the file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
namespace mws
{
class FtpFileUpload
{
static string ftpurl = "ftp://ftp.newsxpressmedia.com/";
static string filename = #"c:\temp\FtpTestFile.txt";
static string ftpusername = "Username";
static string ftppassword = "Password";
static string ftpdirectory = "subtestdir";
public static void test()
{
try
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
ftpurl + "/" + Path.GetFileName(filename));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(ftpusername, ftppassword);
StreamReader sourceStream = new StreamReader(#"c:\temp\test1.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 tried to change the first line and added also a line to create a directory:
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
ftpurl + "/" + ftpdirectory + "/" + Path.GetFileName(filename));
request.Method = WebRequestMethods.Ftp.MakeDirectory;
But then i'm getting exception error:
The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
But before the changes it's working fine no problems.
How can i create a directory on my server first and then upload the file to the created directory ?
Have you checked this answer : How do I create a directory on ftp server using C#?
It looks like the path you're giving to the MakeDirectory request is actually a file name, not a directory name.
public static void CreateDirectoryandSaveImage(string username, string password)
{
string ftphost = "ftp.placemyorder.com";
string filePath = #"D:\ddlState.png";
//You could not use "ftp://" + ftphost + "/FTPUPLOAD/WPF/WPF.txt" to create the folder,this will result the 550 error.
string ftpfullpath = "ftp://" + ftphost + "/TestFolder";
// //Create the folder, Please notice if the WPF folder already exist, it will result 550 error.
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential("ftp.placemyorder.com|placemyorder", "Cabbage123");
ftp.UsePassive = true;
ftp.UseBinary = true;
ftp.KeepAlive = false;
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse CreateForderResponse = (FtpWebResponse)ftp.GetResponse();
if (CreateForderResponse.StatusCode == FtpStatusCode.PathnameCreated)
{
//If folder created, upload file
var fileName = Path.GetFileName(filePath);
string ftpUploadFullPath = "ftp://" + ftphost + "/TestFolder/" + fileName;
FtpWebRequest ftpUpLoadFile = (FtpWebRequest)FtpWebRequest.Create(ftpUploadFullPath);
ftpUpLoadFile.KeepAlive = true;
ftpUpLoadFile.UseBinary = true;
ftpUpLoadFile.Method = WebRequestMethods.Ftp.UploadFile;
ftpUpLoadFile.Credentials = new NetworkCredential(username, password);
ftpUpLoadFile.UsePassive = true;
ftpUpLoadFile.UseBinary = true;
ftpUpLoadFile.KeepAlive = false;
FileStream fs = File.OpenRead(filePath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftpUpLoadFile.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
}
This is what they say about using the ftp:
http://www.ipage.com/controlpanel/FTP.bml
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.
This is the method i'm trying now:
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)WebRequest.Create(ftpurl);
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();
}
}
}
}
But i'm getting exception on the line:
Stream requestStream = request.GetRequestStream();
The exception:
The requested URI is invalid for this FTP command
The complete exception error message:
System.Net.WebException was caught
HResult=-2146233079
Message=The requested URI is invalid for this FTP command.
Source=System
StackTrace:
at System.Net.FtpWebRequest.GetRequestStream()
at ScrollLabelTest.FtpFileUploader.test() in e:\test\test\test\FtpFileUploader.cs:line 36
InnerException:
Line 36 is:
Stream requestStream = request.GetRequestStream();
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(
ftpUrl + "/" + Path.GetFileName(fileName));
You need to include the filename.
I am using the following code to learn how to load files with FTP. How do I set the path or folder into which my file will be uploaded ?
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
// 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();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
}
}
}
The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.