Upload Files in C#.net Windows Application - c#

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);
}

Related

Copy File to remote windows server using .net core

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

Download file to browser from SFTP server in ASP.NET using SSH.NET

With SSH.NET, I am trying to trigger a file to be downloaded by the browser instead of directly writing it to the local file storage.
using(var saveFile = File.OpenWrite(#"Downloads")) {
result = client.BeginDownloadFile(remotePath + fileName, saveFile) as SftpUploadAsyncResult;
client.EndUploadFile(result);
}
The above code fails as my the application pool identity doesn't have permission to write files and I cannot give permission as I don't have Admin privileges to my computer.
So better option would be to trigger the download through browser which was working earlier with FtpWebRequest.
But my current task is to convert the FTP download to SFTP download.
Can someone suggest the best way to trigger browser download?
Download the file to HttpResponse.OutputStream:
HttpResponse response = HttpContext.Current.Response;
response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
client.DownloadFile(remotePath + fileName, response.OutputStream);

Stream file from FTP server using FluentFTP to web client in ASP.NET Core

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.

Save files to external(other domain server) server in asp.net

Is it possible to save file to other domain path from file control. I have 2 website www.domain1.com & www.domain2.com. Now I have file control in www.domain1.com & here I want to upload a file which will be store in some directory of www.domain2.com. I don't know is it possible or not. I am trying below basic code but it's not working
if (mainImageUploader.FileName != "")
{
System.IO.FileInfo file = new System.IO.FileInfo(mainImageUploader.PostedFile.FileName);
string newname = file.Name.Remove((file.Name.Length - file.Extension.Length));
newname = (newname + System.DateTime.Now.ToString("_ddMMyyhhmmss")) + file.Extension;
mainImageUploader.SaveAs(Server.MapPath("http://www.domain2.com/images/client-store/" + path + newname));
}
No, not possible if your other server is configured anywhere near correctly.
You need to enable endpoint on your other server to provide file upload. And probably need to secure it somehow - i.e. with username/password.
It's not possible. The better way is creating a WebApi to save file on its server on your second website and save file via calling it from your first website.
Each web server only let to each website to access to its root and subfolders or files.

Moving files on the server side using webservice

I am working on a requirement that has the following logic. code is in C# and .NET CF 3.5
Upload some files from a mobile device to a web server.
when the upload is successful, the file is moved to an archived folder on the mobile device.
Download some files from the server to the mobile device.
When the download is successful, the file has to be moved to an archived folder on the server side in order so as not to download the same file again.
Wrote a web service (asmx) to handle this operation. The uploading and downloading works fine.
The webservice uses the function FileInfo.MoveTo() to move the file from the downloaded folder to the archives on the web server.
This works locally fine (when the webservice and the client calling the webservice are hosted on the same machine) but when deployed to a server, I get this message "the process cannot access the file because it is being used by another process".
I have given the necessary permissions to the IIS account on the server side. I would like to know if that can be achieved at all from the mobile device or is there any other way to invoke that call on the mobile device. I need to execute this method immediately after the file is downloaded.
Sample code is attached.
fileEntriesD = SomeWebService.FilesList();
string[] extractedFiles = fileEntriesD.Split(',');
foreach (string fileName in extractedFiles)
{
//dothe file downloading
//code comes here.......
}
//move the file on the server once all the files are downloaded
foreach (string DumpfileName in extractedFiles)
{
//after the download is complete move the file to the archived folder
string MoveFileOnServerStatus;
MoveFileOnServerStatus = SomeWebService.MoveFileToArchive(DumpfileName);
MessageBox.Show(MoveFileOnServerStatus);
}
code for the WebMethod for MoveFileToArchive(DumpfileName)
[WebMethod(Description="move the file to the archive location")]
public string MoveFileToArchive(string fileArchiveName)
{
try
{
string SerPathD = GetLocationOfFiles + "\\" + "ArchivedDispatchedFiles";
FileInfo MFTA = new FileInfo(SerPathD + "\\" + fileArchiveName);
MFTA.MoveTo(SerPathD + "\\" + fileArchiveName);
}
catch(IOException ex)
{
//if there is any error then return the error message.
return ex.Message.ToString();
}
//if the moving was successful then return 1 to the client.
return "1";
}

Categories