Change file permission after FTP Upload - c#

I am uploading files in a folder on the desktop to the Windows Server 2012 server.
The upload is proceeding correctly, but I need to change the read and delete permission of the uploaded file.
How can I do this in this code?
string ftpIPServidor = "XXXX";
string ftpUsuarioID = "XX";
string ftpSenha = "XXXXXXX";
FileInfo _arquivoInfo = new FileInfo(_nomeArquivo);
string uri = "ftp://" + ftpIPServidor + "/" + _arquivoInfo.Name;
FtpWebRequest requisicaoFTP;
requisicaoFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpIPServidor + "/" + _arquivoInfo.Name));
requisicaoFTP.Credentials = new NetworkCredential(ftpUsuarioID, ftpSenha);
requisicaoFTP.KeepAlive = false;
requisicaoFTP.Method = WebRequestMethods.Ftp.UploadFile;
requisicaoFTP.UseBinary = true;
requisicaoFTP.ContentLength = _arquivoInfo.Length;
// Define o tamanho do buffer para 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int _tamanhoConteudo;
FileStream fs = _arquivoInfo.OpenRead();
var horaAgora = DateTime.Now;
try
{
Stream strm = requisicaoFTP.GetRequestStream();
_tamanhoConteudo = fs.Read(buff, 0, buffLength);
while (_tamanhoConteudo != 0)
{
// Escreve o conteudo a partir do arquivo para o stream FTP
strm.Write(buff, 0, _tamanhoConteudo);
_tamanhoConteudo = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
Console.WriteLine(horaAgora + " :> Upload of " + _arquivoInfo.Name);
fi.Delete();
}
catch (Exception ex)
{
Console.WriteLine(horaAgora + " :> Err " + _arquivoInfo.Name);
}

There are extension methods called GetAccessControl and SetAccessControl in the package System.IO.FileSystem.AccessControl
More info here
How to modify file access control in .NET Core

Related

FTP Server generates "Error: 150 Opening data channel for file download"

I have write code for transfer file from FTP server to local server and after transfer 2 or 3 files it throwing exception error The remote server returned an error: 150 Opening data channel for file download
All File transfered successfully in FileZila but error coming in asp.net application.
I do the following code
protected string TransferFile(string strPath, string strFtpPath, string strFtpUser, string strFtpPwd, string strSubClientFTPPath, string strSubClientFTPUser, string strSubClientFTPPwd, string strFileName, string strConvFileName, string strFileSize)
{
string strSuccess = "";
FtpWebRequest reqFTP;
try
{
Double Size = 0;
string strLocalFileSize = "";
if (File.Exists(strPath + strConvFileName))
{
Size = ((Math.Round(Convert.ToDouble(new FileInfo(strPath + strConvFileName).Length)) > 0 && Math.Round(Convert.ToDouble(new FileInfo(strPath + strConvFileName).Length)) < 1024) ? 1 : (Math.Round(Convert.ToDouble(new FileInfo(strPath + strConvFileName).Length) / 1024 + 0.0001)));
strLocalFileSize = Size + "KB";
}
if (!File.Exists(strPath + strConvFileName) || strFileSize != strLocalFileSize)
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpPath + strFileName.Replace("#", "%23")));
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
reqFTP.EnableSsl = true;
reqFTP.Timeout = Timeout.Infinite;
reqFTP.KeepAlive = true;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
//reqFTP.UseBinary = true;
//reqFTP.UsePassive = false;
reqFTP.Credentials = new NetworkCredential(strFtpUser, strFtpPwd);
// lblTransferredFile.Text = "Transferring " + strFileName + " ......";
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
// lblTransferredFile.Text = "Transferring " + strFileName + " ......";
readCount = ftpStream.Read(buffer, 0, bufferSize);
//if (readCount > 0)
//{
FileStream outputStream = new FileStream(strPath +
strConvFileName, FileMode.Create);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
strSuccess = "";
}
else
{
strSuccess = "File Exists";
}
}
catch (Exception ex)
{
strSuccess = ex.Message;
ClientScript.RegisterStartupScript(this.GetType(), "strScript", "<script>alert('" + ex.Message.Trim().Replace("'", "") + "');</script>");
}
return strSuccess;
}
I've encountered this today after installing kb 4519976. Uninstalling this KB solved the problem. Could you check if this is also the solution in your case.
Context was an ftps tls 1.2 ECHDE connection which fails at the stage where the extra connection is started.

"The operation has timed out in ftp" this error occurs when downloading a zip file with slow network from the server

I am using ftp for downloading a zip file(size 10 MB to 70 MB) from server it was perfectly downloading but, when the network is slow, the error the operation has timed out in ftp is showing and then it comes to catch(Exception ex) in that the download() is called once again so it is redownloading again and again.
This project is created in .NET framework 4.0
I have increased the time of ftpWebRequest.Timeout = 6000; but still it doesn't work
public void Download(string localDirectory,string localFilename,string remoteDirectory,string remoteFileName)
{
string client_path=Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(localDirectory)));
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string configFile = System.IO.Path.Combine(appPath, "PACS.exe.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["client_path"].Value = client_path;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
string str = Path.Combine(localDirectory, localFilename);
FileInfo fileInfo = new FileInfo(str);
FileStream fileStream = (FileStream)null;
WebException webException;
try
{
string path = Path.GetDirectoryName(Path.GetDirectoryName(remoteDirectory));
string path1 = Path.GetDirectoryName(Path.GetDirectoryName(localDirectory));
WebRequest sizeRequest = WebRequest.Create("ftp://" + "IP" + ":" + "port" + "/" + "C:\\KINSOLUTIONS\\Team\\Images\\1" + ".zip");
sizeRequest.Credentials = (ICredentials)new NetworkCredential("UserName", "Password");
sizeRequest.Method = WebRequestMethods.Ftp.GetFileSize;
int size = (int)sizeRequest.GetResponse().ContentLength;
FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri("ftp://" + "IP" + ":" + "port" + "/" + "C:\\KINSOLUTIONS\\Team\\Images\\1" + ".zip")) as FtpWebRequest;
ftpWebRequest.Credentials = (ICredentials)new NetworkCredential("UserName", "Password");
ftpWebRequest.UsePassive = true;
ftpWebRequest.Timeout = 6000;
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = "RETR";
ftpWebRequest.UseBinary = true;
fileStream = new FileStream(path1 + ".zip", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
using(Stream responseStream = (ftpWebRequest.GetResponse() as FtpWebResponse).GetResponseStream())
{
byte[] buffer = new byte[32768];
int count = responseStream.Read(buffer, 0, 32768);
long num = (long)count;
int post = 0;
while (size != post || count != 0 )
{
bool result = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
while (!result)
{
result = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (result)
{
fileStream.Close();
Download(localDirectory, localFilename, remoteDirectory, remoteFileName);
}
}
fileStream.Write(buffer, 0, count);
count = responseStream.Read(buffer, 0, 32768);
int position = (int)fileStream.Position;
num += (long)count;
post = position;
}
fileStream.Close();
}
}
catch (WebException ex)
{
if (fileStream != null)
fileStream.Close();
this.Download(localDirectory, localFilename, remoteDirectory, remoteFileName);
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
Is there any other option for downloading the zip file in slow network?

How to rename a file after upload

I have to upload file using Ftp protocol on server, and rename uploaded file after uploading.
I can upload it, but don't know how to rename it.
Code looks like this:
FtpWebRequest requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + fileName));
requestFTP.Proxy = null;
requestFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword);
requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fStream = fileInfo.OpenRead();
int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
Stream uploadStream = requestFTP.GetRequestStream();
int contentLength = fStream.Read(buffer, 0, bufferLength);
while (contentLength != 0)
{
uploadStream.Write(buffer, 0, contentLength);
contentLength = fStream.Read(buffer, 0, bufferLength);
}
uploadStream.Close();
fStream.Close();
requestFTP = null;
string newFilename = fileName.Replace(".ftp", "");
requestFTP.Method = WebRequestMethods.Ftp.Rename; // this like makes a problem
requestFTP.RenameTo(newFilename);
Error I'm getting is
Error 2 Non-invocable member 'System.Net.FtpWebRequest.RenameTo'
cannot be used like a method.
RenameTo is a property, not a method. Your code should read:
// requestFTP has been set to null in the previous line
requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + fileName));
requestFTP.Proxy = null;
requestFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword);
string newFilename = fileName.Replace(".ftp", "");
requestFTP.Method = WebRequestMethods.Ftp.Rename;
requestFTP.RenameTo = newFilename;
requestFTP.GetResponse();
Why not just upload it with the correct filename in stead? Change your first line with the filename you actually want.
FtpWebRequest requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + newFileName));
But do open the reading stream from your old filename.

c# asp.net FTP Error

I get "System.NotSupportedException: The given path's format is not supported. at System.Security.Util.StringExpressionSet" when trying to download an item from an ftp(which have access to). The upload seems to work fine and is done similarly I'll post both functions below:
private void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
//filePath = <<The full path where the file is to be created. the>>,
//fileName = <<Name of the file to be createdNeed not name on FTP server. name name()>>
Label1.Text = filePath + "/" + fileName;
FileStream outputStream = new FileStream(filePath + "/" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri("ftp://" + ftpServerIP + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP +"/" + fileInf.Name));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "Upload Error");
}
}
and these are the function calls
protected void btnDownload_Click(object sender, EventArgs e)
{
string FullServer = "ftp://" + ftpServerIP;
Download(FullServer, LbxServer.SelectedValue);
}
protected void btnUpload_Click(object sender, EventArgs e)
{
Upload(LbxLocal.SelectedValue);
}
Thank you all for any help on this matter.
I think you'll find that ftp://myservername is an invalid scheme for a new FileStream. Note that your FileStream represents the local target, not the remote file.
If your intent is to download a remote file to your local system, filePath should refer to a folder on your local network (e.g., C:\temp or \\somecomputer\share, etc.)

Upload a file with encoding using FTP in C#

The following code is good for uploading text files, but it fails to upload JPEG files (not completely - the file name is good but the image is corrupted):
private void up(string sourceFile, string targetFile)
{
try
{
string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
//string ftpURI = "";
string filename = "ftp://" + ftpServerIP + "//" + targetFile;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
StreamReader stream = new StreamReader(sourceFile);
Byte[] b = System.Text.Encoding.UTF8.GetBytes(stream.ReadToEnd());
stream.Close();
ftpReq.ContentLength = b.Length;
Stream s = ftpReq.GetRequestStream();
s.Write(b, 0, b.Length);
s.Close();
System.Net.FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
MessageBox.Show(ftpResp.StatusDescription);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I have another solution that can upload a file:
private void Upload(string sourceFile, string targetFile)
{
string ftpUserID;
string ftpPassword;
string ftpServerIP;
ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
FileInfo fileInf = new FileInfo(sourceFile);
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)(FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "//" + targetFile)));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
// Bypass default lan settings
reqFTP.Proxy = null;
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
Byte[] buff;
buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
long filesize = fs.Length;
int i=0;
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
Application.DoEvents();
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
i = i + 1;
//Double percentComp = (i * buffLength) * 100 / filesize;
//ProgressBar1.Value = (int)percentComp;
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}
But here I have the opposite problem - the picture is good, but the file name is corrupted.
I know it is because of the encoding, but I don't know how to make the bytes array have the desired encoding...
Try this bit:
private static void up(string sourceFile, string targetFile)
{
try
{
string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
////string ftpURI = "";
string filename = "ftp://" + ftpServerIP + "//" + targetFile;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
byte[] b = File.ReadAllBytes(sourceFile);
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
MessageBox.Show(ftpResp.StatusDescription);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You should be using a Stream to read binary files, not a StreamReader. StreamReader is designed to read text files only.
In your first code example, enable binary transfer: FtpWebRequest.UseBinary = true. Otherwise it will convert what it thinks are textual line endings between the various platform conventions (but are actually part of the image).
Your second snippet does it the right way. It uses FileStream, not StreamReader. StreamReader is only suitable for text files.
System.Text.Encoding.UTF8.GetBytes(stream.ReadToEnd());
Don't do this unless your stream's contents are text. Change your function to accept a boolean parameter "binary", and use the latter, working method if that flag is set.
If you have this problem: The requested FTP command is not supported when using HTTP
you need set proxy in Null or Nothing.
ftpReq.Proxy = null;
You can see this blog.
http://mycodetrip.com/2008/10/29/fix-for-error-the-requested-ftp-command-is-not-supported-when-using-http-proxy_118/comment-page-1/#comment-2825
Thanks.

Categories