I have put endpoint that accept the zip file. The endpoint is working fine to get the zip file. Now from that endpoint after I get that file I am trying to copy that file to a different remote Server.
I try below code to connect to remote Server using the below code by referring to micrsoft docs https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity.runimpersonated?view=net-6.0:
bool returnValue = LogonUser(#"ACC\Test.test", "acc.local", "password",
9, 0,
out safeAccessTokenHandle);
if (returnValue)
{
WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () =>
{
//Destination remote server folder to upload file
var pathToUploadFile = #"\\152.158.100.45\D\FileUpload";
string fileName;
fileName = file.FileName;
var path = Path.Combine(pathToUploadFile, fileName);
using (var stream = new FileStream(path, FileMode.Create))
{
//save a zip file to folder
file.CopyTo(stream);
}
});
}
In this code I get error of username and password is incorrect in this line of code:
var stream = new FileStream(path, FileMode.Create)
I am not even sure if the LogonUser method connects to a remote server. So is there is better way to do this copy file to remote server Please give an idea to implement in .net core 6.0 C#. Any help is really appreciated. Thanks
Finally I am able to solve the issue by implementing the Win32 API called WNetUseConnection solutions that was mentioned on below questions:
Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials
Related
I have a shared webhosting service which my ASP.NET Core app runs, and an FTP server. I want to serve the files that clients need to download from the site.
I want the files not to be accessible to everyone, so this is what I do (I use FluentFTP):
var cred = new NetworkCredential(_config.UserName, _config.Password);
FtpClient client = new FtpClient(_config.Host, int.Parse(_config.Port), cred);
await client.ConnectAsync();
var remotePath = $"{_config.Folder}{FILE_DIR}/{filename}";
var result = await client.DownloadAsync(remotePath: remotePath, 0L);
await client.DisconnectAsync();
if (result != null)
{
return File(result, "application/force-download", filename)
}
else
{
throw new Exception("Failed");
}
The problem is, the server tries to download the file from the FTP server, then sends it to client. And there is the same problem for upload too, the client needs to upload file to the server, and then server uploads it to the FTP server. I think this can be very time-consuming with large files.
Is there any better way to achieve this goal? Or is it possible to write the file being downloaded from FTP simultaneously to the client response so the client downloads any bit of file downloaded in server and doesn't have to wait for the download to server to finish to start the download?
Thanks in advance.
Download the file directly to the HTTP output stream with use of FtpClient.Download (to be renamed FtpClient.DownloadStream in upcoming versions) and HttpResponse.OutputStream:
Response.AddHeader("Content-Disposition", $"attachment; filename={filename}");
client.Download(Response.OutputStream, remotePath);
(where Response is ASP.NET HttpResponse).
A similar question for native .NET FtpWebRequest/WebClient:
Download file from FTP and how prompt user to save/open file in ASP.NET C#
Also note that the application/force-download seems like a hack.
Use Content-Disposition: attachment to force the download.
I am trying to implement FTP transfer using FluentFTP in C#. Getting a directory listing is very easy, but I am stuck on downloading files.
I found one article that has an example in its comments here but it won't compile because I cannot find where the class FtpFile comes from.
Does anybody have an example of how tocan I download a file from an ftp server using FluentFTP ?
EDIT: I found some examples here https://github.com/hgupta9/FluentFTP But there is no example on how to actually download a file.
In the this article Free FTP Library there is an example but it does not compile. This is the example
FtpClient ftp = new FtpClient(txtUsername.Text, txtPassword.Text, txtFTPAddress.Text);
FtpListItem[] items = ftp.GetListing();
FtpFile file = new FtpFile(ftp, "8051812.xml"); // THIS does not compile, class FtpFile is unknown
file.Download("c:\\8051812.xml");
file.Name = "8051814.xml";
file.Download("c:\\8051814.xml");
ftp.Disconnect();
EDIT: The solution
The article I found contained an example that set me in the wrong direction.
It seems there was once a Download method but that is gone long ago now.
So the answer was to let that go and use the OpenRead() method to get a stream and than save that stream to a file.
There are now DownloadFile() and UploadFile() methods built into the latest version of FluentFTP.
Example usage from https://github.com/robinrodricks/FluentFTP#example-usage:
// connect to the FTP server
FtpClient client = new FtpClient();
client.Host = "123.123.123.123";
client.Credentials = new NetworkCredential("david", "pass123");
client.Connect();
// upload a file
client.UploadFile(#"C:\MyVideo.mp4", "/htdocs/big.txt");
// rename the uploaded file
client.Rename("/htdocs/big.txt", "/htdocs/big2.txt");
// download the file again
client.DownloadFile(#"C:\MyVideo_2.mp4", "/htdocs/big2.txt");
I am using the following code to download file from FTP.
NetworkCredential credential = new NetworkCredential(Properties.Settings.Default.FTPUserName, Properties.Settings.Default.FTPPassword);
string inputfilepath = Path.Combine(Properties.Settings.Default.LocalDownloadFolder, file);
string ftpfullpath = Properties.Settings.Default.FTPSite + Properties.Settings.Default.FTPFolder + file;
WebClient request1 = new WebClient();
request1.Credentials = credential;
request1.DownloadFile(ftpfullpath, inputfilepath);
Values of the first two vaiables is:
E:\FTPDownloads\CardholderManagementReport_1030_2012-12-11.xls
ftp://abc.com/AKSHAY/CardholderManagementReport_1030_2012-12-11.xls
It shows error as :
The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
EDIT:
I can see that the file is indeed present there, credentials are ok and I can download it using FileZilla
The error 550 returned by the FTP server indicates that the user you are using to try and access the file with does not have permission to access the file.
Either use some other set of credentials that has access to the file or change the permissions on the file to allow access.
This makes it work.
ftp://abc.com/%2f/AKSHAY/CardholderManagementReport_1030_2012-12-11.xls
Explaination is also there.
I Want Upload some Files into a Website Host in C#.net Windows Application.what is a Best way To Upload file in Windows Application?
That depends on your server. If it's yours you can make it listen to post requests and upload files through there. If it's not yours there's probably ftp installed, so you can try that.
See here for ftp uploading: http://www.vcskicks.com/csharp_ftp_upload.php
and here for using http post requests: http://en.csharp-online.net/HTTP_Post
i found SVN is the best way so far,
install the client on your local machine and on server. and install the server SNV on your sever.
Server: http://www.visualsvn.com/server/
Client: http://tortoisesvn.net/downloads.html
file upload in C#
HttpPostedFileBase file = this.Request.Files["Upload"];
if (file != null)
{
var fileName = file.FileName;
var fileExtension = Path.GetExtension(fileName);
filePath = fileName.Replace(fileName, emailTemplateImage.token + fileExtension);
var imagepath = Server.MapPath("/Upload/EmailTemplateImage/") + filePath;
if (!System.IO.Directory.Exists(filePath))
{
System.IO.Directory.CreateDirectory(filePath);
}
file.SaveAs(imagepath);
}
How to download a file via web service ? And how the client application accept this?
I write down the code as below in the client app, it throws an exception "Access Denied"
wsDownload.wsDownloadFile downFile = new wsDownload.wsDownloadFile();
byte[] file = downFile.DownloadFile(strFileName, "", "", "");
MemoryStream mStream = new MemoryStream(file);
any response is appreciated.
"Access denied" probably just means the local web service user doesn't have read access to the local copy of the file.
Ron
It's probably a matter of ntfs permissions on the service side. You should grant read permissions on the folder that contains the file you are downloading to the user account under which is running the WS, usually IIS_WPG.