Extra data when uploading txt file to FTP server using C# - c#

Ok, so I am testing uploading files to an FTP server by attempting to upload a text file with the contents of "HELLO WORLD".
I am given a return of"
"upload file completed System.Net.WebClient error -> cancelled ->False".
The file seems to appear on the server but when I open it, the contents read:
--------------8d30e4d69803578
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: application/octet-stream
HELLO WORLD
--------------8d30e4d69803578
the code I am using is:
string ftpUserName = "ftpUserName";
string ftpPassword = "ftpPassword";
string ftpURL = "ftp://ftpServer.com/text.txt";
string path = "pathToFile/test.txt"
public static void Test()
{
System.Uri uri = new System.Uri(ftpURL);
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
return;
}
using(WebClient wc = new WebClient())
{
wc.Credentials = new NetworkCredential(ftpUserName,ftpPassword);
wc.UploadFileCompleted += UploadFileCompleted;
wc.UploadFileAsync(uri,"STOR",path);
}
}
Any help would be appreciated
edit
I also just tried with a zip file and it is corrupt. Both the .txt and .zip are also far smaller once they reach the server, so I am assuming the upload has failed because of that error
edit 2
solved it using .net2.0's version of the FtpWebRequest

I have just verified - other than the async issue I mentioned, there's nothing wrong with your code.

Related

Uploading and downloading small files to a cloud drive in-game? (Unity3D)

I need any player's client to be able to upload and download files (they are text files that have replay data. I'm making a racing game and want players to be able to send and download replays.) while in-game. I'm trying to use Dropbox but I'm having problems. I'm open to other file hosting services but I don't really know how to send and get data from them. I keep making little changes here and there and they all give me different errors. Is there anything I'm doing blatantly wrong here? I'm expecting the main problem to be in the dropbox URL I'm using. Here's what my code looks like:
private void DownloadReplay()
{
string l_playerID = PlayFabManager.load_PlayfabId;
string l_levelID = PlayFabManager.load_levelID;
using (WebClient wc = new WebClient())
{
string path = Path.Combine(Application.persistentDataPath, $"{l_playerID}{l_levelID}.replay");
string url = ("https://www.dropbox.com/s/f786vep0z9yd11s/"+ $"{l_playerID}{l_levelID}");
wc.Credentials = new NetworkCredential("xx", "xx");
wc.DownloadFile((new System.Uri(url)), path);
}
}
private void UploadReplay()
{
string s_playerID = PlayFabManager.load_PlayfabId;
string s_levelID = PlayFabManager.load_levelID;
using (WebClient client = new WebClient())
{
string path = Path.Combine(Application.persistentDataPath, $"{s_playerID}{s_levelID}.replay");
string url = Path.Combine("https://www.dropbox.com/s/f786vep0z9yd11s/" + $"{s_playerID}{s_levelID}");
client.Credentials = new NetworkCredential("xx", "xx");
client.UploadFile(url, path);
}
}
Right now this one gives me an error 404, even though the file matching the string is in my dropbox.

Uploading files to ftp folder having special characters in name

I am trying to upload a file on FTP folder, but getting the following error.
The remote server returned an error: (550) File unavailable (e.g.,
file not found, no access)
I am using the following sample to test this:
// Get the object used to communicate with the server.
string path = HttpUtility.UrlEncode("ftp://host:port//01-03-2017/John, Doe S. M.D/file.wav");
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("user", "password");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(#"localpath\example.wav");
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();
I am able to upload files on the parent folder 01-03-2017 but not in the target folder ROLLINS, SETH S. M.D which clearly has special characters in it.
I am able to upload files using FileZilla
I have tried to HttpUtility.UrlEncode but that did n't help
Thanks for your time and help.
You need to encode the spaces (and maybe commas) in the URL path, like:
string path =
"ftp://host:port/01-03-2017/" +
HttpUtility.UrlEncode("John, Doe S. M.D") + "/file.wav";
Effectively, you get:
ftp://host:port/01-03-2017/John%2c+Doe+S.+M.D/file.wav
Use something like this:
string path = HttpUtility.UrlEncode("ftp://96.31.95.118:2121//01-03-2017//ROLLINS, SETH S. M.D//30542_3117.wav");
or You can form a Uri using the following code and pass it webrequest.
var path = new Uri("ftp://96.31.95.118:2121//01-03-2017//ROLLINS, SETH S. M.D//30542_3117.wav");
The code works on a C# console application but did not work in Web Api Action. I could not manage to find the reason.
So I have used a free library for the same.
Posting the sample code from one of the examples available here:
So i have used FluentFtp libary available through Nuget.
using System;
using System.IO;
using System.Net;
using FluentFTP;
namespace Examples {
public class OpenWriteExample {
public static void OpenWrite() {
using (FtpClient conn = new FtpClient()) {
conn.Host = "localhost";
conn.Credentials = new NetworkCredential("ftptest", "ftptest");
using (Stream ostream = conn.OpenWrite("01-03-2017/John, Doe S. M.D/file.wav")) {
try {
// istream.Position is incremented accordingly to the writes you perform
}
finally {
ostream.Close();
}
}
}
}
}
}
Again, if the file is a binary file, StreamReader should not be used as explained here.

Text Encoding comes out corrupted after downloading from FTP

So i am making a program in c# with .net that uploads text files...
but everytime i upload a text file then download it on filezilla it comes out in chinese looking text..See here. im not sure if its because of encoding but if it helps heres my ftp code:
string ftpUsername = "#######";
string ftpPassword = "##########";
string localFilePath = path+ #"\" +FileName;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://###########/Logs/Text.txt", "STOR", localFilePath);
File.Delete(path + #"\" + FileName);
}
The reason the text file was coming out corrupted was not the upload method but the download method in FileZilla...
When you download you need to set the transfer type too binary...
this gets rid of the issue..

Returning An Xml String To Client Code From C#

I am reading a file from the user files that contains xml that I am processing in a Generic Handler and then passing to the client.
The problem I am having is when I pass the string of xml to the client. Its not in the proper format. It removes the root tag and "<xml 1.0>" tag entirely when looking at it through the client code.
I am looking for some code to preserve the xml string as is when it gets to the client.
I am reading the xml out of a file using System.IO on the server..
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
string path = context.Server.MapPath("~/Temp");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var file = context.Request.Files[0];
string fileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string strFileName = fileName;
fileName = Path.Combine(path, fileName);
file.SaveAs(fileName);
string msg = File.ReadAllText(fileName);
File.Delete(fileName);
context.Response.Write(msg);
}
}
The xml always starts at "Gambardella..." For some reason it cannot read the beginning of the file when being send to the cient.
Here is an image of the sample xml..
The data is sent out of the handler fine but the client cuts off the top information. It looks like the plugin I am using is storing the (or getting) the data from an iframe. Could the iframe maybe be the culprit in cutting off the beginning xml??
The sample client code I am using is here
You can simply use Response.WriteFile, instead of reading the file then sending it.
Response.WriteFile(fileName);
This will return the contents of the file with the correct HTTP Content-Type header. If the file has the XML declaration, it will not remove it.
Something like the following, based on your code and untested (an without a MemoryStream, as it is not needed in this case):
var file = context.Request.Files[0];
file.InputStream.CopyTo(context.Response.OutputStream)

Download file for reading question using HttpWebRequest

If I have a URL to a download, www.website.com/myfile.html
so when that link is clicked it automatically starts a download, which may be myfile.txt for example, how would I get that file into C# for reading..
Is that what Net.WebRequest.Create(url), Net.HttpWebRequest does?
You could achieve this using WebClient:
using (var client = new WebClient())
{
// Download and save the file locally
client.DownloadFile("http://www.website.com/myfile.html", "myfile.html");
}
If you don't want to store the file locally but only read the contents you could try this:
using (var client = new WebClient())
{
string result = client.DownloadString("http://www.website.com/myfile.html");
}
Using C# as an example, here is how one might force the download of a file after clicking a button, link, etc...
public void DownloadFileLink_Click(object sender, EventArgs e)
{
//Get the file data
byte[] fileBytes = Artifacts.Provider.GetArtifact(ArtifactInfo.Id);
//Configure the response header and submit the file data to the response stream.
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment;filename=" + "myDynamicFileName.txt");
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(fileBytes);
HttpContext.Current.Response.End();
}
With this in mind, what you need to look for is the Header in the response, the Header will contain an item Content-disposition which will contain the filename of the file being streamed in the response.

Categories