Error in Deploy webservice FTP C# - c#

Im trying to download files that are inside the FTP server with webservice.
[WebMethod]
public string BrowseFileSimplify(string FileName, string varlocaldirectory)
{
Regex regex = new Regex(#"[a-zA-Z_-]+?\.[a-zA-Z]{1,5}$");
Match match = regex.Match(FileName);
if (match.Success)
{
try
{
string inputfilepath = varlocaldirectory + "\\" + FileName;
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential(UserName, Password);
byte[] fileData = request.DownloadData(uri+FileName);
using (FileStream file = File.Create(inputfilepath))
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
return "Download Success";
}
}
catch (Exception ex)
{
return "Problem with " + ex.Message; //Error en la aplicacion
}
}
else
{
return "Error with file format"; //Error en el formato del archivo
}
}
It works fine when i execute with VisualStudio, it returns "Download Success", but when i upload to web it return:"Error: Unable to connect to the remote server"
I need put some code into web.config?
Thanks in advance

Its likely a networking issue. Would need to know more about the hosting environment to be sure. You would usually start troubleshooting by logging into the server and trying to ping/telnet to the target ftp server and go from there.

Related

access denied while accessing a file in windows shared location

So there two computers (A and B) connected for file shareing. A needs to access a folder from B.
In comp A, in windows explorer below path is working
\B\sharedFolder\file.txt
Successful able to open the file.
But in my .net application .net framework 4.7.2
Same path is not working. Getting access denied.
Please let me know how to access this file.
Tried using network credentials. Didn't work.
To access UNC file shares in a application you have to provide credentials for allowing the application access over the share.
Something like this:
string filePath = #"\\server\share\file.txt";
string username = "username";
string password = "password";
try
{
using (NetworkCredential networkCredential = new NetworkCredential(username, password))
{
using (FileStream fileStream = File.OpenRead(filePath))
{
using (StreamReader reader = new StreamReader(fileStream))
{
string fileContents = reader.ReadToEnd();
Console.WriteLine("File contents: {0}", fileContents);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error reading file: {0}", ex.Message);
}
If you are using an older version of .NET it might not support the using statement for non-disposable objects. You should use this instead:
try
{
NetworkCredential networkCredential = new NetworkCredential(username, password);
FileStream fileStream = File.OpenRead(filePath);
using (StreamReader reader = new StreamReader(fileStream))
{
string fileContents = reader.ReadToEnd();
Console.WriteLine("File contents: {0}", fileContents);
}
}
catch (Exception ex)
{
Console.WriteLine("Error reading file: {0}", ex.Message);
}

Uploading file or creating directory on ftp with unicode characters in name via C#

I need to create file or directory on ftp via C# (in Unity engine). I tried to upload the file this way:
public void upload(string remoteFile, string file_content)
{
try
{
string address = host + #"/текст.txt";
Debug.Log(address); // gives a normal address in Unicode
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(address);
ftpRequest.Credentials = new NetworkCredential(user, pass);
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
ftpRequest.ContentLength = file_content.Length;
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
byte[] byteBuffer = System.Text.Encoding.Unicode.GetBytes(file_content);
try
{
using (ftpStream = ftpRequest.GetRequestStream())
{
ftpStream.Write(byteBuffer, 0, byteBuffer.Length);
Debug.Log(Convert.ToString(byteBuffer));
}
}
catch (Exception ex)
{
ErrorScene.error = "Local Error: 1. " + ex.ToString(); SceneManager.LoadScene("ErrorScene", LoadSceneMode.Single);
}
ftpStream.Close();
ftpRequest = null;
}
catch (Exception ex)
{
ErrorScene.error = "Local Error: 2. " + ex.ToString(); SceneManager.LoadScene("ErrorScene", LoadSceneMode.Single);
}
return;
}
And after this function call in ftp creates a file named ?????.txt.
Similarly with directories.
Is there a way to do this?
Thanks in advance.

Get confirmation or error after FTP upload

Using the script below, I uploaded a file to a FTP server. It worked, but would be nice if the script would also show a message box with a confirmation if the upload is successful. Or a message box displaying an error code if the upload failed. Any help please?
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://example.com/target.txt", "STOR", localFilePath);
}
I know I should do something like this:
byte[] responseArray = client.UploadFile("ftp://example.com/target.txt", localFilePath);
string s = System.Text.Encoding.ASCII.GetString(responseArray);
I just don't know how to put the pieces toghether.
You could try to use a Try & Catch
https://msdn.microsoft.com/en-us/library/xtd0s8kd(v=vs.110).aspx
Ok, found a good solution to this:
bool exception = false;
try
{
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(FtpUser.Text, FtpPass.Text);
client.UploadFile("ftp://example.com/file.txt", "STOR", MyFilePath);
}
}
catch (Exception ex)
{
exception = true;
MessageBox.Show(ex.Message);
}
if(!exception){
MessageBox.Show("Upload worked!");
}

Can't reinstall service

I am trying to create an auto update for an application however I am having a bit of trouble with the updating part. Basically what I have is a windows service that periodically checks for updates and when it finds and update it launches a console application to update itself. The code for the console application is below.
The problem I'm having is that when I uninstall the service and replace the file that drives the service, I get a system.badimageformat exception. Despite reinstalling an identical file. If I uninstall and re-install the file without downloading it and replacing it from FTP there is no issue, but as soon as I change the file it starts giving me exceptions. Does anyone have any ideas on how I can work around this error. I am confident its not a 32 vs 64 bit issue which is what commonly causes this error.
static void Main(string[] args)
{
if (!System.Diagnostics.EventLog.SourceExists("OCR Updater"))
{
EventLog.CreateEventSource("OCR Updater", "Application");
}
ServiceController sc = new ServiceController("OCR Scheduler", ".");
if (sc.Status == ServiceControllerStatus.Running)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
}
ProcessStartInfo Uninstallpsi = new ProcessStartInfo();
Uninstallpsi.Verb = "runas";
Uninstallpsi.UseShellExecute = false;
Uninstallpsi.FileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "installutil.exe";
Uninstallpsi.Arguments = " /u " + "\"" + AppDomain.CurrentDomain.BaseDirectory.ToString() + "OCR_Scheduler_Service.exe\"";
Process.Start(Uninstallpsi);
Console.WriteLine("Sleeping Thread after uninstall");
System.Threading.Thread.Sleep(10000);
OCRUpdater program = new OCRUpdater();
List<string> Files = program.GetFiles();
foreach (string item in Files)
{
if (item.ToString() == "Sqlite" || item.ToString() == "License.xml")
{
continue;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.mccinnovations.com/OCR_Scheduler/V2Updates/Files/" + item);
request.Method = WebRequestMethods.Ftp.DownloadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("ftp admin", "_Stingray_12");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string[] temp = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
reader.Close();
response.Close();
string DesktopFile = "";
try
{
DesktopFile = #"C:\Users\hnelson\Desktop\" + item;
if (File.Exists(DesktopFile))
{
File.Delete(DesktopFile);
}
File.WriteAllLines(DesktopFile, temp);
}
catch (Exception ex)
{
EventLog.WriteEntry("OCR Updater", "Error in file path" + DesktopFile + ex.Message);
continue;
}
try
{
File.Delete(#"C:\Program Files (x86)\MCCi\OCR Scheduler V2\" + item);
System.Threading.Thread.Sleep(2000);
File.Copy(DesktopFile, #"C:\Program Files (x86)\MCCi\OCR Scheduler V2\" + item, true);
File.Delete(DesktopFile);
EventLog.WriteEntry("OCR Updater", DesktopFile);
}
catch (Exception)
{
EventLog.WriteEntry("OCR Updater", DesktopFile);
EventLog.WriteEntry("OCR Updater", "Error in file path " + #"C:\Program Files (x86)\MCCi\OCR Scheduler V2\" + item);
continue;
}
}
try
{
System.Threading.Thread.Sleep(5000);
ProcessStartInfo psi = new ProcessStartInfo();
psi.Verb = "runas";
psi.UseShellExecute = false;
psi.FileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "installutil.exe";
psi.Arguments = " " + "\"" + AppDomain.CurrentDomain.BaseDirectory.ToString() + "OCR_Scheduler_Service.exe\"";
Process.Start(psi);
}
catch (Exception ex)
{
EventLog.WriteEntry("OCR Updater", "Could not reinstall service" + ex.Message + ex.InnerException);
}
System.Threading.Thread.Sleep(10000);
Console.WriteLine("Finished resinstalling the service.");
try
{
string[] serviceStartArgs = { "true" };
sc.Start(serviceStartArgs);
sc.WaitForStatus(ServiceControllerStatus.Running);
}
catch (Exception ex)
{
EventLog.WriteEntry("OCR Updater", "Could not start the service after install" + " " + ex.Message + ex.InnerException);
}
}
public List<string> GetFiles()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.mccinnovations.com/OCR_Scheduler/V2Updates/Files/");
request.Method = WebRequestMethods.Ftp.ListDirectory;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("ftp admin", "_Stingray_12");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
List<string> Files = new List<string>();
while (reader.EndOfStream == false)
{
Files.Add(reader.ReadLine());
}
reader.Close();
response.Close();
return Files;
}
}
}
The main problem is that you treat the files as text files:
string[] temp = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
....
File.WriteAllLines(DesktopFile, temp);
You can use this instead:
Stream responseStream = response.GetResponseStream();
...
using (FileStream destStream = File.Create(DesktopFile))
{
responseStream.CopyTo(destStream);
}
responseStream.Close();
response.Close();
However, this is still not the best solution, since you should use the pattern
using (X123 x123 = new X123(y))
{
// do something with x123
}
for all classes which support IDisposable.
In addition, I have some concerns about using Sleep() in so many situations. This is seldom a good idea.

FTP Upload image error

I am trying to upload images to my ftp server hosted by a web hosting to store users profile images for when they close and re open my application
Note If there is any other way I can store it please suggest it
I have tryed the following code below but I keep receiving a error saying
An unhandled exception of type 'System.Net.WebException' occurred in App.exe Additional information: The remote server returned an error: (500) Syntax error, command unrecognized
A comment a person said to me was "That error is quite generic. It could mean you have a firewall or something blocking something or it can mean that SSL is not supported on the server" Could any of you help towards this comment. Because I don't understand how i can block the firewall or stop it or excreter excreter (Not that important help if you can)
Carrying on to the main problem ... My code - (FTP Part) In a public static class
public static void UpLoadImage(string source)
{
try
{
String sourcefilepath = source;
String ftpurl = "ftp://www.locu.site90.com/public_html/";
String ftpusername = "a4670620";
String ftppassword = "********";
string filename = Path.GetFileName(source);
string ftpfullpath = ftpurl + filename;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = false;
ftp.EnableSsl = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(source);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
}
catch (Exception ex)
{
throw ex;
}
}
And here is where I call the void when selecting a image
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == DialogResult.OK)
{
Bitmap bit = new Bitmap(open.FileName);
pictureBox1.Image = bit;
pictureBox2.Image = bit;
bit.Dispose();
string fullPath = open.FileName;
string fileName = open.SafeFileName;
string path = fullPath.Replace(fileName, "");
User.Details.UpLoadImage(fullPath);
}
}
Any help given is 100% appreciated from me myself!
I am using the following code to create the path:
System.Net.FtpWebRequest ftpReq = null;
System.Net.FtpWebResponse ftpRes = null;
try
{
ftpReq = System.Net.WebRequest.Create(path) as System.Net.FtpWebRequest;
ftpReq.Credentials = new System.Net.NetworkCredential(user, password);
ftpReq.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory;
ftpReq.KeepAlive = false;
ftpRes = ftpReq.GetResponse() as System.Net.FtpWebResponse;
ftpRes.Close();
}
catch (WebException we)
{
//do something with the error
}
catch (Exception e)
{
//do something with the error
}
and to upload the file why you don't use
public byte[] UploadFile(string address, string fileName):
Code for uploading to ftp:
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(tabFolder.FldUser, tabFolder.FldPassword);
wc.UploadFile(folder.TrimEnd(#"\".ToCharArray()) + #"\" + fn, jpgFile);

Categories

Resources