Upload file to server .Net - c#

I am using C# .net and I am trying to upload a file to my server. I am not using asp .net.
I followed This Question and it doesn't seem to work for me. On a sidenote, this question was written back in 2008.
I am using this code as shown in the question above:
File.Copy("zQn69PZUx.png", "\\\\198.57.247.152\\~shiro\\public_html\\new");
//tried this also
File.Copy("zQn69PZUx.png", "\\\\198.57.247.152\\~shiro\\new");
The error I get:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The network path was not found.
I also tried using my domain name and use the path like it shows up in the browser, without http:// because it complained about the format, saying its not accepted, like this: domain-name.com\\new, and still got the same error as a result.
Any ideas what I could be doing wrong, or have a better solution on how to upload a file to a server ? You can see here that the http://198.57.247.152/~shiro/new/ path exists.

The path \\198.57.247.152\~shiro\new is what Microsoft calls Uniform Naming Convention (UNC). This type of resource is only available on networks with NetBIOS enabled; essentially local network. The problem is that File.Copy only works if you have access to it in your network - since this is a remote server, it won't be able to find that server, leading to the The network path was not found exception.
http://198.57.247.152/~shiro/new/ follows the syntax of <scheme name> : <hierarchical part> [ ? <query> ] [ # <fragment> ] which is call Uniform resource locator (URL). Hypertext Transfer Protocol (http) resource is typical accessed by a browsers.
You can resolve this by instead using FTP to upload your file to the server:
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://ftpserver.com/targetpath", "localfilepath");
}
A valid target path would be something like: ftp://localhost/samplefile.txt
and the local filepath should be the fully qualified filepath.

You can upload file using code from Peter Luu's answer. But first you should have access to it.
For uploading a file to a remote server, you should be a user of it and should have a password. It is not the password you use for logging in to your Hostgator control panel. After logging into your Hostgator account, there will be an option like FTP in it, where you can setup FTP user accounts. There you can assign a user name and password and that have to be applied to the code for uploading..
And for checking whether the UserName and Password works, Open MyComputer, and in the addressbar type the FTP path (which will be something starting "ftp://"). There pops up a Dialog asking for UserName and Password (If the path is valid). If you enter into, See and copy files into the explorer window from there, then the uploading code will work
If you want to get the applicable path, Open windows explorer and type ftp://your_domain_name. Apply UserName and Password, browse through the path you need, copy it from the address bar and add it to the code.

Related

Check if file from remote server exists

i have an application which requires access permission to a file on remote server.
My app is in Server A, and the file i want to access is in Server B. These 2 servers are in the same domain.
I created a virtual directory in Server A for the directory in Server B. The name of virtual directory is FolderFromServerB and its path is \ServerB\Folder. I use a user for auth, and when i test the connection in IIS it says all is OK.
Also, when i put an anchor tag in a test file like below, i can access the file and the content is shown in the page:
Test file --> **This works**
But my problem is when i use code in order to if that file exists or not, it always returns with False. My code is like below:
FileInfo fi = new FileInfo(#"\FolderFromServerB/test.txt"); --> This doesn't work
Response.Write(fi.Exists); --> This always 'False'
I granted 'Full Control' permission to my user& NETWORK SERVICE & Everyone & Administratos in Server B but i didnt work neither.
How can i make it work?
It was working last week. I guess the server updated itself and some updates made that occur, but i couldn't find any workaround. Im so desperate now and i have to change all of my code and spend much time to make it work.
I found the workaround that is in web.config :
<identity impersonate="true" userName="{domain}\{username}" password="{password}"/>
I used File.Exist() for a few months, but then suddenly it was gone and didnt work, and i dont know why. But it is the solution above.
Your code does not work because the current execution folder of an ASP.Net application is not the folder of you application, but c:\windows\system32.
When you create the FileInfo object, you will try to read c:\windows\system32\FolderFromServerB\test.txt.
The <a href="FolderFromServerB/test.txt"> works because the link will be relative to the current page (it won't works if the page is in another directory).
If the file you are looking for is under your application directory, you can convert a virtual to a physical path using :
string actualFilePath = HttpContext.Current.Server.MapPath("~/FolderFromServerB/test.txt");
FileInfo fi = new FileInfo(actualFilePath);

How do you open a file on a server using different user account credentials

I'm currently developing a C# WinForms application in VS2012 (.NET 4.0). The application is a bit like an Email client and displays a list of messages. And each message can have one or one files attached.
The file attachments are stored on a different server, which can only be accessed using another user account (and not by the logged on user).
When the user double clicks on a File Attachment I need to open the file and display it in the associated application. i.e. TXT files in Notepad, DOCX files in Word, etc.
I was hoping I could just pass the full file name into the System.Diagnostics.Process.Start method, with the correct username, password and domain values and it would open the file in the associated application.
e.g.
SecureString password = new SecureString();
"MyPassword".ToCharArray().ToList().ForEach(password.AppendChar);
System.Diagnostics.Process.Start(#"\\MyServer\MyFolder\MySubFolder\MyFile.docx",
"MyUsername",
password,
"MyDomain");
But an exception is thrown with the message:
The specified executable is not a valid application for this OS platform.
I've also tried creating a ProcessStartInfo object instance and setting the FileName property to "Explorer.exe" and the Arguments property to #"\\MyServer\MyFolder\MySubFolder\MyFile.docx", and passing it as the parameter into the System.Diagnostics.Process.Start method. But this doesn't work either. No exception is thrown and the file isn't displayed either.
But if you look at the object returned by the System.Diagnostics.Process.Start method you see that an InvalidOperationException has occurred.
My C# question is, how can I open and display a file (in it's associated application), when the file is stored on a server that can only be accessed using different user credentials?
I think this should work
Step 1. Find the App registered with the extension
Step 2. Use the same Api that was mentioned
System.Diagnostics.Process.Start("App from the current Machine that was found in step 1",
#"\MyServer\MyFolder\MySubFolder\MyFile.docx",
"MyUsername",
password,
"MyDomain");
See the following links of how to find the register app for an extension
How to get recommended programs associated with file extension in C#
http://www.codeproject.com/Articles/17023/System-File-Association

Permission error when uploading files

I have the following code:
var saveFolder = Path.Combine(Properties.Settings.Default.DropBoxFolder, guid.ToString("N"));
// Create folder, if it does not exist (for the first attachment, it shouldn't exist)
if (!Directory.Exists(saveFolder))
{
Directory.CreateDirectory(saveFolder);
}
var saveFilePath = Path.Combine(saveFolder, file.FileName);
file.SaveAs(saveFilePath);
I'm using GUIDs to generate folders for uploads on my IIS server. The .NET web application is configured to impersonate the user. I granted modify permissions to the target folder (it is a local path on the web server) for Domain Users, Local Service and Everyone, but some users still can't upload files. I can and other people on my team can.
The weird part is that the exception says this:
Could not find a part of the path 'C:\Users\USERID\Desktop\FILENAME'
That path is the path to the file the user selected to upload (their local file path). I feel it is safe to say that the user has permission to his own file on his own desktop. I don't use user impersonation much, so I am wondering what I missed in my configuration or permissions. Any suggestions for debugging this issue? Thanks!
Note: the CreateDirectory method works just fine, even when the exception is thrown. I would have thought that if the user didn't have permission the directory creation would have failed first.

Why am I recieving this error: "Could not find a part of the file '...' "?

What I am trying to accomplish is to upload some files from one domain on my shared hosting to another domain on the same hosting where the files will be displayed. When I debug the application, the process gets to the SaveAs() method and then throws the exception,"Could not find a part of the path ..." .
I have followed these instructions on finding my site's folder's absolute path and I have implemented this path in my code, using the same method I've been using for a good part of my file uploading, and I have never ran into any problems. My read/write permissions are allowed for the folder that I'm attempting to save these files in.
I'm wondering "Is it because I'm trying to upload the file to a different directory?". If so, is there a better way to accomplish this?
var fileName = Path.GetFileName(file.FileName);
var path = #"D:\Hosting\someNumbers\html\SiteFile\SiteImages\" + fileName;
file.SaveAs(path);
myObject.FilePath1 = path;
Any help will be highly appreciated.
As it turns out, my error was more or less a security issue with GoDaddy's hosting. GoDaddy sees this type of action as a "third party FTP request", which is not allowed. In conclusion, GoDaddy does not allow a user to upload a file on one site, and then FTP that file to another site on the same hosting plan.

Read file on a remote server

I have a file on a remote server and I want to read this file.
lets say the files location is:
string filePath = #"\\192.168.101.15\c$\program files\xxx\test.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
This code is for sure throwing an error:
Logon failure: unknown user name or bad password.
How can I pass my credentials??
if I go start/run and put this path, I need to provide credentials lets say Admin and password 123.
Im using Asp.net, c# 3.5
Any Ideas
You have to use impersonation, ie execute your code with a user who has acces to the shared folder instead of asp.net user :
http://msdn.microsoft.com/en-us/library/aa292118%28VS.71%29.aspx
You have two way :
-with code
-with configuration
Your application will need to run as a user that has access to the UNC path, or else impersonate a user with such permissions, for the file load operation.
You'd need to be pre-authenticated on the share before you can access the files. It isn't something you can do just by passing a UNC path.
You might consider executing a net use command via the shell programatically. That's the only way I can find to do this.

Categories

Resources