Copy file fo mapped network drive using FileInfo.CopyTo - c#

I try to copy a file to a mapped network drive, but I always get the message "Could not find a part of the path ...". I tried different mapped network drives, so I could exclude credential problems (it neither works with a drive connexcted with different credentials nor with my normal user)
try
{
fi.CopyTo(SystemReg.TargetPath + fi.Name);
}
catch (Exception e)
{
SystemReg.Log.AppendLine("Copy failed! " + Environment.NewLine + e.Message);
}
SystemReg.TargetPath is read from an XML file. If I use a local path like D:\temp\ it works perfectly, but e.g. X:\temp\ with X as a mapped drive it fails.
I also tried to run my program in a batch file with "net use..." before calling my program, it also fails.

You shoud use computer address instead of drive name.
For example, if your computer's address is 192.168.0.200 which keeps shared folder temp\ then your full path is \\192.168.0.200\temp\

Related

C# Windows Services File Move to different directory

Apparently changing codes blows my head.
Here's what i am facing at the moment.
I've developed a service that will extract data from an SQL which converts the data into a CSV file and then upload the file via WinSCP. Once upload finishes , the file is then moved to another directory.
However we had an upgrade and i no longer able to extract the Data from SQL as user have to manually download the file and put into my folder.
I then changed my code to remove the SQL part , and kept sequence starting from the Upload file via WinSCP.
However , now my file move no longer works with error :
File Name couldnt be changed because : Could not find file 'Q:\FrontOffice\Nights\Qualtrics\UNPROCESSED\import-contacts.csv'.
Is there any reason why it cannot find that file when the file and path exist?
Note 1 : The Windows Services is installed in a Server environment. The Server has access to the network drive with admin credentials.
Note 2 : User only need to place the file into Unprocessed folder while the service will process the file and move it to Processed folder.
Here is my previous file move code :
string attachFileLoc = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\import-contacts-"+ DateTime.Today.AddDays(-1).ToString("yyyyMMdd") + ".csv";
var filename = Path.GetFileName(attachFileLoc);
try
{
System.IO.File.Move(#"C:\Users\Administrator\Documents\Automation\csvfiles\import-contacts.csv", attachFileLoc);
WriteToFile("New File name is : " + filename);
}
catch (System.Exception ex)
{
WriteToFile("File Name couldnt be changed because : " + ex.Message);
}
I then modified my code to reflect to our NAS network folder.
string attachFileLoc = #"Q:\FrontOffice\Nights\Qualtrics\PROCESSED\import-contacts-" + DateTime.Today.AddDays(-1).ToString("yyyyMMdd") + ".CSV";
try
{
System.IO.File.Move(#"Q:\FrontOffice\Nights\Qualtrics\UNPROCESSED\import-contacts.csv", attachFileLoc);
WriteToFile("New File name is : " + filename);
}
catch (System.Exception ex)
{
WriteToFile("File Name couldnt be changed because : " + ex.Message);
}
I then tried to use other methods to obtain file location and name
string[] qfile = Directory.GetFiles(#"Q:\FrontOffice\Nights\Qualtrics\UNPROCESSED\", "*.CSV").FirstOrDefault();
try
{
System.IO.File.Move(qfile[0], attachFileLoc);
WriteToFile("New File name is : " + filename);
}
catch (System.Exception ex)
{
WriteToFile("File Name couldnt be changed because : " + ex.Message);
}
but this one didnt even manage to obtain file name and location.
Edit 1 requested by mjwills :
Edit 2 requested by Caius Jard :
[Solution]
I ran debug and tried to use trycatch method to see what is going on.
Apparently I did not have enough privilege level as per conversation before with others in this thread.
I added the server into Domain as my NAS is also in a domain.
I also added the Windows Services to Log On as a Domain user.
I then proceeded to try removing the mapped drive from the Server. This does not work.
It does work when i have mapped drive or if i do mapping in my code , both while the installed services is in a Server that is in a Domain.
Conclusion :
Windows Services does use mapped drive but windows services authentication is not the same as the User Logged in or the same as the user that has the services installed with.
Solution :
Add LogOn Option to the windows services matching the network drive authentication
i.e : If Network Drive is a NAS in Domain , LogOn option should add Domain ID that has access to the required folder.
i.e2 : If Network Drive is a Shared Folder from PC21 , LogOn option should be an ID that has authentication to the required folder in PC21.

How to write to an iSeries FileShare from ASP.Net

I've written an asp.net webapp that writes a file to a location on our iSeries FileShare.
The path looks like this: \IBMServerAddress\Filepath
This code executes perfectly on my local machine, but fails when it's deployed to my (windows) WebServer.
I understand that i may need to do some sort of impersonation to authenticate access to the IFS, but i'm unsure of how to proceed.
Here's the code i'm working with:
string filepath = "\\\\IBMServerAddress\\uploads\\";
public int SaveToDisk(string data, string plant)
{
//code for saving to disk
StreamWriter stream = null;
stream = File.CreateText(filepath + plant + ".txt"); // creating file
stream.Write(data + "\r\n"); //Write data to file
stream.Close();
return 0;
}
Again, this code executes perfectly on my local machine but does not work when deployed to my Windows WebServer - access to filepath is denied.
Thanks for your help.
EDIT: I've tried adding a network account with the same credentials as the IFS user, created a UNC path (iseries)on IIS7 to map the network drive (using the same credentials) - but receive this error:
Access to the path 'iseries\' is denied.
My understanding of Windows in general is that normally services don't have access to standard network shares like a program being run by a user does.
So the first thing would be to see if you can successfully write to a windows file share from the web server.
Assuming that works, you'll need one of two things in order to write to the IBM i share..
1) An IBM i user ID and password that matches the user ID and password the process is being run under
2) A "guest account" configured on IBM i Netserver
http://www-01.ibm.com/support/knowledgecenter/ssw_ibm_i_71/rzahl/rzahlsetnetguestprof.htm
You might have better luck with using Linux/UNIX based Network File System (NFS) which is supported in both Windows and the IBM i.

Environment.GetFolderPath(Environment.SpecialFolders.ApplicationData) returns C:

I have encountered a very strange behavior on the computer of one of my clients and I cannot find any clue as to why it happens:
When the application calls Environment.GetFolderPath(Environment.SpecialFolders.ApplicationData)
the return value will be C:.
This is of course wrong, his AppData directory is the usual C:\Users\.....\AppData\Roaming and also his variable %APPDATA% points to exactly that directory.
Can anybody shed light on why this could possibly happen?
EDIT: The code...
LogFilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\ReportsAddin";
if (!Directory.Exists(LogFilePath) && Properties.Settings.Default.Logging == true)
{
try
{
Directory.CreateDirectory(LogFilePath);
}
catch (Exception ex)
{
// ...
}
}
The exception thrown then says that it cannot create a directory consisting of a blank string or blank spaces. Investigating with some output showed that the AppData folder returning from that call is C: when in fact it should be the user's real AppData folder.
The actual path for the folder identified by Environment.SpecialFolder.ApplicationData depends on the current user (who started the program).
Make sure the program runs under a user account for which the ApplicationData folder exists.
If your program runs under e.g. a local system account you may want to use another directory.
Instead of Environment.SpecialFolder.ApplicationData you could use Environment.SpecialFolder.CommonProgramFiles or Environment.SpecialFolder.CommonProgramFilesX86.

Copying files to a mapped drive while user is not logged in (scheduled task)

I have a job that needs to connect to two fileshares and copy some files for a data feed.
The source server is on our domain's network, and that works fine. The remote server, however, chokes on me and throws a "Could not find part of the path" error. I should add the destination server lives in a different domain than my source server.
The source and destination paths are read out of my app.config file.
I thought persistently mapping a drive would work, but since this is a scheduled task, that doesn't seem to work. I thought about using NET USE, but that doesn't seem to like taking a username and password.
The really weird thing - if I double click on the job while I'm logged into the machine, it'll run successfully.
Sample code:
DirectoryInfo di = new DirectoryInfo(srcPath);
try
{
FileInfo[] files = di.GetFiles();
foreach (FileInfo fi in files)
{
if(!(fi.Name.Contains("_desc")))
{
Console.WriteLine(fi.Name + System.Environment.NewLine);
File.Copy(fi.FullName, destPath + fi.Name, true);
fi.Delete();
}
}
}
Apparently this isn't as simple as copying the files over. Any suggestions on mapping a drive with credentials in C# 4.0?
EDIT
I'm trying to use a batch file called from the console application that maps the drive while the program is running. I'll know for sure whether that works in the morning.
I'd suggest looking into a proper file transfer protocol, like FTP.
Assuming that's out of the question, try using a UNC path like \\servername\path\file.txt. You will still need credentials, but assuming that the account running the application has those permissions you should be fine. Given that you mention a web.config file, I am guessing that would be an ASP.NET application, and therefore I mean the account that runs the Application Pool in IIS. See http://learn.iis.net/page.aspx/624/application-pool-identities/
What I finally wound up doing was mapping the drive in a batch file called by my program. I just launch a NET USE command and pause for a few seconds for the mapping to complete.
It looks like while the user is logged out, there's no context around mapped drives.

Reading File From Network Location

I am having Bunch of Files in A folder which is shared on Network Drive . I am trying to Access those Files into my Code . But It is giving an error:
System.IO.DirectoryNotFoundException was unhandled by user code
Fname = txtwbs.Text;
DirectoryInfo objDir = new DirectoryInfo("Y:\\");
_xmlpath = objDir + "\\" + Fname + "\\" + Fname + ".xml";
if (File.Exists(_xmlpath ))
{
reader(_xmlpath);
}
I have Also used:
file = fopen("\\\\10.0.2.20\\smartjobs\\Eto\\"+Fname);
I am Able to Read File from My Local PC But it is giving Exception Only for Network Location .Please let me know how can I read File From Network Shared Location .
And Also How Can I Make A tree view of Folders into Asp.net Web Application .
Directory Structure is Like that
\\10.0.2.20\Smartjobs\Eto\
this is Parent Directory It is congaing Nos of Folder having XML Documents.
In asp.net, you cannot access network folder directly because asp.net runs under anonymous user account, that account does not have access to that location.
You can give rights to "Everyone" in that shared location and see if it is working. However this is not advisable.
Alternativly You may have to do impersonation in asp.net code when accessing network location. You will have to do implersonation with the user who has access to that shared location.
You may have map the shared directory as a user, but you forget that the asp.net is running under the account of the pool, and there you do not have connect the y:\ with the shared directory.
The next think that you can do is to direct try to connect via the network shared name, eg: \\SharedCom\fulldir\file.xml
You need to specify that the ASP.net page run as a certain user with access to the file. Then, you need to enable impersonation in your web.config file in order for ASP.net to actually access the file as that user.
Your Y drive is a mapped network drive. You need to use the network
url eg \\server\Smartjobs\Eto\xyz.xml
You specify the name of the file on the network just like you do from anywhere else:
Dim myStream As IO.FileStream = IO.File.Open("\\myserver\myshare\myfile", IO.FileMode.Open)
Dim myBytes As Byte()
myStream.Read(myBytes, 0, numberOfBytesToRead)
More reference:
Unable to List File or Directory Contents on ASP.NET Page using Shared Drive
Using file on network via IIS

Categories