How to rename a file after upload - c#

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.

Related

Change file permission after FTP Upload

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

Zip file is not getting downloaded using asp.net

I have a folder in which there are 3-4 pdf files. SO on button click, I want to download PDF files as a ZIP file. For that I have write the below code
string strFilePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID + "\\" + SAP_ID + '_' + CANDIDATEID + ".pdf");
string strDirectory = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
if (Directory.Exists(strDirectory))
{
if (File.Exists(strFilePath + ".zip"))
{
var filestream = new System.IO.FileStream(strFilePath + ".zip", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
File.Delete(strFilePath + ".zip");
}
}
// ZipFile.CreateFromDirectory(strDirectory, strDirectory + ".zip");
var stream = new FileStream(strDirectory + ".zip", FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(strDirectory + ".zip");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = stream.Length;
But on button click the ZIP is not getting downloaded and the browser just loads.
Please help me know what is the cause ?
You may have more luck with the Response.TransmitFile method, here is an example using the address of your zip file -
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=file.zip");
Response.TransmitFile(strFilePath + ".zip");
Response.Flush();
If the zip file isn't getting created you probably need to grant write/modify permissions on your UploadedFiles directory to IIS AppPool\yourAppPoolName .

asp net error the process cannot access the file because it is being used

I have an error with regards to the subject above, basically I am just downloading a file from its path. My download code is this:
string sFile = Request.QueryString["RFBNumber"].ToString();
string sFile2 = Request.QueryString["FolderName"].ToString();
string sFlag = Request.QueryString["Flag"].ToString();
//CreateRFBReport(sFile, sFile2);
//CreateSingleFile(sFile2, sFile);
if (sFlag == "1") {
sFilename = "RFB_" + sFile + "_COLLATED.PDF";
sGlobalFolderName = sFile2;
sFilePath = # "" + sGlobalFolderName + "\\" + sFilename;
WebClient client = new WebClient();
byte[] buff = client.DownloadData(sFilePath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buff.Length.ToString());
Response.BinaryWrite(buff);
}
if (sFlag == "2") {
sFilename = "SOP_" + sFile + "_COLLATED.PDF";
sGlobalFolderName = sFile2;
sFilePath = # "" + sGlobalFolderName + "\\" + sFilename;
WebClient client = new WebClient();
byte[] buff = client.DownloadData(sFilePath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buff.Length.ToString());
Response.BinaryWrite(buff);
}
I have to refresh the page multiple times before I can download the item, however I am having an error on the line byte[] buff = client.DownloadData(sFilePath);
Can anyone help me please? Been searching a way to solve this issue. Thank you in advance.

download file from ftp server?

protected void LinkButton1_Click(object sender, EventArgs e)
{
string filename = #"C:\inetpub\ftproot\RetailAgreement\abc.JPG";
string ftpServerIP = "192.148.10.10";
string ftpUserID = "username";
string ftpPassword = "password";
System.IO.FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/RetailAgreement/" + fileInf.Name;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/RetailAgreement/" + fileInf.Name));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
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();
}
here i am getting the exception
FileStream fs = fileInf.OpenRead();
Could not find file 'C:\inetpub\ftproot\' ..
but my path is existed correct path ,i given..what we change above code,please help me?

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