FTP - Uploading a file in a diffrent name - c#

I have a form which has radiobuttons, each of them is giving a file name in a string, and what I want to do is to have that string as a name for any file that a user uploads.
It'll be great if you could explain to me how to rename, because I already got it the code to upload or just help me modify this function, I would probably have to add to the parameters "string type" tho:
public void uploadFTP(string filename, string type, string password, ProgressBar progressbar)
{
WebClient client = new WebClient();
client.Credentials = new System.Net.NetworkCredential("username", password);
try
{
client.UploadFileAsync(new Uri(#"ftp://ftpaddress.com" + "/" + new FileInfo(filename).Name), "STOR", filename);
}
catch(System.InvalidCastException)
{
// Handled it
}
catch (System.ArgumentException)
{
// Handled it
}
client.UploadProgressChanged += (s, e) =>
{
progressbar.Value = e.ProgressPercentage;
};
client.UploadFileCompleted += (s, e) =>
{
MessageBox.Show("Upload complete", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
};
}
If it's important: The files are RTF (RichTextBox).
Thanks!

Just upload to different URL then. Replace new FileInfo(filename).Name in your code with the name you actually want. Also, I think not using string manipulation is better. And the STOR command is the default.
client.UploadFileAsync(new Uri(new Uri("ftp://ftpaddress.com"), newName)), filename);

Related

How can I show/find downloaded image from xamarin.ios in iPhone?

We have written a code to download images from uri using webclient in xamarin.ios. When we download an image it's not displayed in Gallery/Photo app, or in any other location of the iPhone.
Here is my download code:
public void DownloadFiles()
{
try
{
var webClient = new WebClient();
webClient.DownloadDataCompleted += (s, e) => {
var bytes = e.Result;
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = "downloaded.png";
string localPath = Path.Combine(documentsPath, localFilename);
Console.WriteLine("localPath:" + localPath);
File.WriteAllBytes(localPath, bytes);
// IMPORTANT: this is a background thread, so any interaction with
// UI controls must be done via the MainThread
InvokeOnMainThread(() => {
// imageView.Image = UIImage.FromFile(localPath);
UIAlertView alert = new UIAlertView()
{
Title = "alert title",
Message = "Download successfully"
};
alert.AddButton("OK");
alert.AddButton("Cancel");
alert.Show();
});
};
var url = new Uri("https://www.xamarin.com/content/images/pages/branding/assets/xamagon.png");
webClient.DownloadDataAsync(url);
}
catch(Exception e)
{
throw e;
}
}
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
how to find this path?
We have added these permission in info.plist to solve this problem. "Privacy - Photo Library Additions Usage Description" and "Privacy - Photo Library Usage Description"

BackgroundTransfer cannot move files

I am having problem downloading files using Background transfer. After completion of download when moving file, it gives you an exception Operation not permitted
void addTransferRequest(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return;
string filePathToDownload = string.Empty;
filePathToDownload = activeReciter.DownloadURL;
filePathToDownload += fileName;
Uri transferUri = new Uri(Uri.EscapeUriString(filePathToDownload),
UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new
BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
Uri downloadUri = new Uri(DataSource.TEMPDOWNLOADLOCATION + fileName,
UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = fileName;
transferRequest.TransferStatusChanged +=
new EventHandler<BackgroundTransferEventArgs>
(transfer_TransferStatusChanged);
transferRequest.TransferProgressChanged += new
EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
try
{
BackgroundTransferService.Add(transferRequest);
chapterFileNames.Dequeue();
}
catch (InvalidOperationException)
{
}
catch (Exception)
{
}
}
void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
{
ProcessTransfer(e.Request);
}
void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
{
}
private void ProcessTransfer(BackgroundTransferRequest transfer)
{
switch (transfer.TransferStatus)
{
case TransferStatus.Completed:
if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
{
using (IsolatedStorageFile isoStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
string filename = transfer.Tag;
string folderPath = string.Format(#"{0}{1}\{2}\",
DataSource.DOWNLOADLOCATION, activeReciter.ReciterID, chapter.ChapterID);
string fileFullPath = folderPath + filename;
if (!isoStore.DirectoryExists(Path.GetDirectoryName(folderPath)))
isoStore.CreateDirectory(Path.GetDirectoryName(folderPath));
if (isoStore.FileExists(fileFullPath))
isoStore.DeleteFile(fileFullPath);
isoStore.MoveFile(transfer.DownloadLocation.OriginalString, fileFullPath);
//Excpetion is thrown here
RemoveTransferRequest(transfer.RequestId);
}
catch (Exception ex)
{
MessageBox.Show("Error Occured: " + ex.Message + transfer.Tag, "Error",
MessageBoxButton.OK);
return;
}
}
}
break;
}
}
When moving file, it throws exception, I don't know what is wrong with moving (this happens on some of the files not all files).
From the MSDN Page, under File System Restrictions section:
You can create any additional directory structure you choose
underneath the root “/shared/transfers” directory, and you can copy or
move files after the transfer is complete to ensure that the
background transfer service does not modify the files, but attempting
to initiate a transfer using a path outside of the “/shared/transfers”
directory will throw an exception.
Make sure you are not trying to move your file outside from the /Shared/Transfers folder.

WebClient freeze after download

I'm facing another problem, my application downloads a file from a web, extracts it, deletes it and so on, it runs fine for the first run, then when it comes to downloading the next file it simply freezes the download and hangs there forever.. It's probably something with trying to open an already open connection, but I have no idea how to close it, this is my first time networking with C# and I'm self teaching.
My code:
public void start() {
if (File.Exists("Data/version.txt")) { File.Delete("Data/version.txt"); }
label1.Text = "Getting update information...";
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("http://127.0.0.1/update/version.txt"), #"Data/version.txt");
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(versionCompleted);
}
private void versioncheck() {
if (File.Exists("Main.exe"))
{
label1.Text = "Contacting update server...";
var versionInfo = FileVersionInfo.GetVersionInfo("Main.exe");
string version = versionInfo.ProductVersion;
string[] nversion = version.Split('.');
string updateversion = nversion[3];
int version = Int32.Parse(updateversion);
///////////////////////////////////////////////////////////
StreamReader sr = new StreamReader("Data/version.txt");
///////////////////////////////////////////////////////////
string readline = sr.ReadLine();
sr.Dispose();
int serverversion = Int32.Parse(readline);
if (serverversion > version) {
string filenumber = (version+1).ToString();
downloadfile(filenumber);
}
else if(serverversion == version){
label1.Text = "Game is up to date!";
startButton.Enabled = true;
}
}
else { MessageBox.Show("Unexpected Error!", "Error!"); }
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
label1.Text = "Extracting Files...";
var versionInfo = FileVersionInfo.GetVersionInfo("Main.exe");
string version = versionInfo.ProductVersion;
string[] nversion = version.Split('.');
string updateversion = nversion[3];
int version = Int32.Parse(updateversion); string nversion = (version + 1).ToString();
Process proc = Process.Start("update"+nversion+".exe"); // extract in the silent mode
proc.WaitForExit();
File.Delete("update" + nversion + ".exe");
label1.Text = "Checking for more updates...";
versioncheck();
}
private void versionCompleted(object sender, AsyncCompletedEventArgs e) {
versioncheck();
}
private void downloadfile(string filenumber)
{
try
{
//MessageBox.Show("Download working");
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.OpenRead("http://127.0.0.1/Update/update" + filenumber + ".exe");
Int64 bytes_total = Convert.ToInt64(webClient.ResponseHeaders["Content-Length"]);
string updatelength = Convert.ToString((bytes_total / 1024).ToString());
label2.Text = "File size:" + updatelength + "KB";
////////////////////////////////////////////////////
label1.Text = "Downloading Update...";
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri("http://127.0.0.1/Update/update" + filenumber + ".exe"), #"update"+filenumber+".exe");
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.Dispose();
}
catch (WebException )
{
MessageBox.Show("Connection error!", "Error!");
Application.Exit();
}
catch (IOException)
{
MessageBox.Show("Unknown Error!", "Error!");
Application.Exit() ;
}
}
If u use async operation u gonne need to use the async and await keywords.
U need to dispose or close your webclient when it is done downloading or failing.
As b1tsh1ft stated best thing is to use the using statement.
string version = versionInfo.ProductVersion;
string[] nversion = version.Split('.');
int version = Int32.Parse(updateversion);
string nversion = (version + 1).ToString();
Isn't your VS not giving a conflicting error in your editor about this ?
First you should put WebClient in a using block because it implements IDisposable
using(var webClient = new WebClient())
{
// do work here
webClient.DownloadFile(..)
}
Don't use the async version. An exception is likely being thrown and is lost on the other thread. Test and make it work regularly first.
Also put your StreamReader (or anything implementing IDisposable) in a using() statement. It is more reliable then manually calling dispose because it disposes even on failure.

Download a File if it exists on server

I have this code:
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("http://MySite.com/Desktop/Pics.png"),
#"c:\users\Windows\desktop\DesktopsPics\Desktop.png");
My Program will download a .png picture every day as "Daily Pics" in a folder! So, when a user clicks on a button, if "Daily Pic" is already exists in server, the program will download this file.
I can do this with the above code, but, if Pic.Png is not already exists in server, my program throws an error. It downloads a .html file that reads 404 not found.
How can I download a file, if this file exist on a server?
Since you are downloading the file Async, you will need to add an event handler for when the download is completed. Then you can inspect the arg for errors.
Try this:
static void Main(string[] args)
{
WebClient client = new WebClient();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
string fileName = Path.GetTempFileName();
client.DownloadFileAsync(new Uri("https://www.google.com/images/srpr/logo11w.png"), fileName, fileName);
Thread.Sleep(20000);
Console.WriteLine("Done");
}
private static void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
// inspect error message for 404
Console.WriteLine(e.Error.Message);
if (e.Error.InnerException != null)
Console.WriteLine(e.Error.InnerException.Message);
}
else
{
// We have a file - do something with it
WebClient client = (WebClient)sender;
// display the response header so we can learn
foreach(string k in client.ResponseHeaders.AllKeys)
{
Console.Write(k);
Console.WriteLine(": {0}", client.ResponseHeaders[k]);
}
// since we know it's a png, let rename it
FileInfo temp = new FileInfo((string)e.UserState);
string pngFileName = Path.Combine(Path.GetTempPath(), "DesktopPhoto.png");
if (File.Exists(pngFileName))
File.Delete(pngFileName);
File.Move((string)e.UserState, pngFileName); // move to where ever you want
Process.Start(pngFileName);
}
}

fileupload newline in constant

I get the problem newline in constant:
protected void UploadButton_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString();
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/) + filename);
//here
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
Im also wondering is there a way I can resize the image upon upload if so, how?
And as this is a save as in my fileupload control will this overwrite any folder that has the userid already there? (what I want and need)
Newline in constant
FileUploadControl.SaveAs(Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/) + filename);
//here
Should be:
FileUploadControl.SaveAs(Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/") + filename);
//here
Image resize / thumbnails
If it's a thumbnail image you're after, then you can use Image.GetThumbnailImage. A basic implementation is like this:
using (System.Drawing.Image fullsizeImage =
System.Drawing.Image.FromFile(originalFilePath))
{
// these calls to RotateFlip aren't essential, but they prevent the image
// from using its built-in thumbnail, which is invariably poor quality.
// I like to think of it as shaking the thumbnail out ;)
fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
using (System.Drawing.Image thumbnailImage =
fullsizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero))
{
thumbnailImage.Save(newFilePath);
}
}
Overwrite
Overwrite is the default behaviour, so uploading the same file to the same UserID will replace it.
Well I can already see in the line above your error you are missing a quote after /uploadedimage/ and the next to last paren should be after filename not /uploadedimage/
Are you missing a quote or is it a typo:
Server.MapPath("~/userdata/"+theUserId+"/uploadedimage/")
I would also recommend using string.Format when using lots of string concatenation (usually do this when I have to use + more than once):
Server.MapPath(string.Format("~/userdata/{0}/uploadedimage/", theUserId))
EDIT: to answer resize comment:
Here is a link to a similar SO question:
how to resize an image whileing saving in an folder
Which value has the newline variable?
Below adds a Trim() to the value collected and also provides a way to see what each of the string values collected afterwards are.
protected void UploadButton_Click(object sender, EventArgs e)
{
string theUserId = Session["UserID"].ToString().Trim(); // add Trim()
if (FileUploadControl.HasFile && !String.IsNullOrEmpty(theUserId)) // add test
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
Console.WriteLine(filename);
string filepath = string.Format("~/userdata/{0}/uploadedimage/", theUserId);
Console.WriteLine(filepath );
string mapPath = Server.MapPath(filepath);
Console.WriteLine(mapPath );
FileUploadControl.SaveAs(mapPath + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
Just Trim() the string value has the newline constant in it.

Categories