System.UriFormatException' occurred in System.dll error [duplicate] - c#

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

Related

Save file in a folder on another server location with the purely written code on website

I am using mvc I am trying to save a file on another folder i.e on another server.
But earlier i was using an approach of creating two different solution and was saving the file using web request.
i was sending the request from one solution and was geeting it on another solution.
here is my code
byte[] bytes;
var pic = System.Web.HttpContext.Current.Request.Files["ImagePath"];
/*Creating the WebRequest object using the URL of SaveFile.aspx.*/
System.Net.HttpWebRequest webRequest =
(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create
("http://localhost:13492/Home/SaveImage");
webRequest.Method = "POST";
webRequest.KeepAlive = false;
/*Assigning the content type from the FileUpload control.*/
webRequest.ContentType = pic.ContentType ;
/*Creating the Header object.*/
System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();
headers.Add("FileName", pic.FileName);
/*Adding the header to the WebRequest object.*/
webRequest.Headers = headers;
/* Convert File Into byte array */
using (var stream = new MemoryStream())
{
pic.InputStream.CopyTo(stream);
bytes = stream.ToArray();
}
/*Getting the request stream by making use of the GetRequestStream method of WebRequest object.*/
using (System.IO.Stream stream = webRequest.GetRequestStream())//Filling request stream with image stream.
{
/*Writing the FileUpload content to the request stream.*/
stream.Write(bytes, 0, pic.ContentLength);
}
/*Creating a WebResponse object by calling the GetResponse method of WebRequest object.*/
using (System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse())
{
/*Retrieving the response stream from the WebResponse object by calling the GetResponseStream method.*/
using (System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream()))
{
string path = sr.ReadToEnd();
}
}
then in another solution i was getting it to save the file.
public void SaveImage()
{
try
{
/*Retrieving the file name from the headers in the request. */
string destinationFileName = Path.Combine(#"~/" + "Portfolio" + "/", Request.Headers["FileName"].ToString());
string fileName = System.Web.HttpContext.Current.Server.MapPath(destinationFileName);
//string path = System.IO.Path.Combine(Server.MapPath("."), Request.Headers["FileName"].ToString());
using (System.IO.FileStream fileStream = System.IO.File.Create(fileName))
{
/*Getting stream from the Request object.*/
using (System.IO.Stream stream = Request.InputStream)
{
int byteStreamLength = (int)stream.Length;
byte[] byteStream = new byte[byteStreamLength];
/*Reading the stream to a byte array.*/
stream.Read(byteStream, 0, byteStreamLength);
/*Writing the byte array to the harddisk.*/
fileStream.Write(byteStream, 0, byteStreamLength);
}
}
Response.Clear();
/*Writing the status to the response.*/
Response.Write(fileName);
}
catch (Exception ex)
{
/*Writing the error message to the response stream.*/
Response.Clear();
Response.Write("Error: " + ex.Message);
}
}
So what should i change in code so that i could save the file on another location on another server without writing the code on two different place.
I've got a solution for this problem and its working fine.
public static void UploadFtpFile(string folderName, string fileName)
{
FtpWebRequest request;
try
{
//string folderName;
//string fileName;
string absoluteFileName = Path.GetFileName(fileName);
request = WebRequest.Create(new Uri(string.Format(#"ftp://{0}/{1}/{2}", "ftp.site4now.net", folderName, absoluteFileName))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = true;
request.Credentials = new NetworkCredential("Username", "Password");
request.ConnectionGroupName = "group";
using (FileStream fs = System.IO.File.OpenRead(fileName))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Flush();
requestStream.Close();
}
}
catch (Exception ex)
{
}
}
Follow Below Sample
This sample is for creating a folder on another server over FTP protocol. Please extend it as per need.
using System;
using System.Net;
class Test
{
static void Main()
{
WebRequest request = WebRequest.Create("ftp://host.com/directory");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("user", "pass");
using (var resp = (FtpWebResponse) request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
}
}
As per the comment by #ADyson you must enable the FTP Protocol before working using this sample

how to upload documents to sharepoint 2007 C#

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);
}
}

C# Upload file with no extension

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.

How can i create a directory on my ftp server before uploading a file to my ftp?

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();
}
}

How do i upload a file to my ftp at weebly.com?

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.

Categories

Resources