473,406 Members | 2,956 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

How Do I move a file over a network?

55
I would like to know how I can move a file over a network using C#?
I tried this :
Expand|Select|Wrap|Line Numbers
  1.  case "218":
  2.           Console.WriteLine("Backing up " + filename.ToString() + "....");
  3.           fileinfo.CopyTo("\\\\118.9.11.11" + backUpLocation);
  4.           break;
  5.  
But I keep getting a System.UnauthorizedAccessException: Access to the path is denied. execption

Please Help
Jul 21 '08 #1
6 1099
Curtis Rutland
3,256 Expert 2GB
Do you have the proper permissions to that location?
Jul 21 '08 #2
napstar
55
Yes I do have all the required permissions on both locations.I can read from from one location but I cant seem to write to a different folder(shared) on the networked computer.
Jul 21 '08 #3
Plater
7,872 Expert 4TB
You might have the correct access, but its quite apparent that your program does NOT have the correct access.
Jul 21 '08 #4
napstar
55
How do I correct this?
Jul 21 '08 #5
Plater
7,872 Expert 4TB
How do I correct this?
That's a good question. You're the second person to ask this type of question recently. While I vaguely recall something about how to do it long ago, I cannot seem to find anything about it now.

I guess for starters, if this is a web application, you could use the identity impersonate thing in the web.config. For a windows application...I am not sure. Maybe something in the machine.config file?
Jul 21 '08 #6
I had the same problem, and this is what I found.
It's a bit of a struggle, but it works

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Security.Principal;
  4. using System.IO;
  5.  
  6. namespace RemoteCredentials
  7. {
  8. class MainClass
  9. {
  10. [DllImport( "advapi32.dll", SetLastError = true )]
  11. private static extern bool LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken );
  12.  
  13. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  14. private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *arguments);
  15.  
  16. [DllImport( "kernel32.dll", CharSet = CharSet.Auto, SetLastError = true )]
  17. private static extern bool CloseHandle( IntPtr handle);
  18.  
  19. [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  20. public extern static bool DuplicateToken( IntPtr existingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr duplicateTokenHandle );
  21.  
  22.  
  23. // logon types
  24. const int LOGON32_LOGON_INTERACTIVE = 2;
  25. const int LOGON32_LOGON_NETWORK = 3;
  26. const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
  27.  
  28. // logon providers
  29. const int LOGON32_PROVIDER_DEFAULT = 0;
  30. const int LOGON32_PROVIDER_WINNT50 = 3;
  31. const int LOGON32_PROVIDER_WINNT40 = 2;
  32. const int LOGON32_PROVIDER_WINNT35 = 1;
  33.  
  34. /// <summary>
  35. /// The main entry point for the application.
  36. /// </summary>
  37. [STAThread]
  38. static void Main(string[] args)
  39. {
  40. IntPtr token = IntPtr.Zero;
  41. IntPtr dupToken = IntPtr.Zero;
  42.  
  43. bool isSuccess = LogonUser("userID", @"\\100.100.100.100\d$", "PassWd", LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token);
  44. if (!isSuccess)
  45. {
  46. RaiseLastError();
  47. }
  48.  
  49. isSuccess = DuplicateToken( token, 2, ref dupToken );
  50. if( !isSuccess )
  51. {
  52. RaiseLastError();
  53. }
  54.  
  55. WindowsIdentity newIdentity;
  56. WindowsImpersonationContext impersonatedUser = null;
  57. DirectoryInfo dirInfo;
  58. FileInfo[] files;
  59.  
  60. try
  61. {
  62.  
  63. newIdentity = new WindowsIdentity(dupToken);
  64. impersonatedUser = newIdentity.Impersonate();
  65.  
  66. dirInfo = new DirectoryInfo(@"\\100.100.100.100\d$\Test folder");
  67. files = dirInfo.GetFiles();
  68. }
  69. finally
  70. {
  71. impersonatedUser.Undo();
  72. }
  73.  
  74. foreach( FileInfo file in files )
  75. {
  76. Console.WriteLine( file.FullName );
  77. }
  78.  
  79. isSuccess = CloseHandle( token );
  80. if( !isSuccess )
  81. {
  82. RaiseLastError();
  83. }
  84. Console.ReadLine();
  85. }
  86.  
  87. // GetErrorMessage formats and returns an error message
  88. // corresponding to the input errorCode.
  89. public unsafe static string GetErrorMessage( int errorCode )
  90. {
  91. int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
  92. int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
  93. int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
  94.  
  95. int messageSize = 255;
  96. string lpMsgBuf = "";
  97. int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
  98.  
  99. IntPtr ptrlpSource = IntPtr.Zero;
  100. IntPtr ptrArguments = IntPtr.Zero;
  101.  
  102. int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref lpMsgBuf, messageSize, &ptrArguments);
  103. if( retVal == 0 )
  104. {
  105. // throw new ApplicationException(string.Format( "Failed to format message for error code '{0}'.", errorCode ) );
  106. Console.WriteLine(string.Format("Failed to format message for error code '{0}'.", errorCode));
  107. }
  108.  
  109. return lpMsgBuf;
  110. }
  111.  
  112. private static void RaiseLastError()
  113. {
  114. int errorCode = Marshal.GetLastWin32Error();
  115. string errorMessage = GetErrorMessage(errorCode);
  116.  
  117. //throw new ApplicationException( errorMessage);
  118. Console.WriteLine(string.Format("Error: {0}", errorMessage));
  119. }
  120. }
  121. }
Jul 22 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Bill Young via .NET 247 | last post by:
I'm having all sorts of problems trying to move a file across the network using the File.Move command with a computer on the network. I have tried doing it with \\<server>\<share> and I tried mapping...
2
by: Eje | last post by:
I have a webapplication on a server. One function is to build txt-files. These files should then be moved to a fixed directory on another computer in the company network. I have tried to use...
1
by: Matthew Eno | last post by:
I have a problem where I'm developing some code that moves files from one place to another (on the same drive) with the destination file having a new name. What's happening is that the line of...
10
by: dermot | last post by:
I have wrriten a small windows service application in visual studio ..net 2003 which listens for incoming FTP files. These files would overwrite over time due to duplicate file names. However any...
0
by: Andy Klare | last post by:
I am looking for a way to copy a file from a local drive on the server to a network share but I need to authenticate as a user that has access to the network share. How can I tie a different set...
8
by: =?Utf-8?B?VG9t?= | last post by:
Hi, I need to copy and/or move files across servers to the other side of my firewall. I was wondering if anyone can tell me what port(s) I will need to open to run these methods in my C#...
3
by: coffeebasket | last post by:
I have created an Windows Service application, and it is suppose to move downloaded files from localdir to a network dir but it fails. The same code in a consol application works just fine. I have...
3
by: jaeden99 | last post by:
I was wandering if nyone has a script to move files older than x days old? i've seen several to delete, but I don't want to delete. I would like to create a backup of the files first verify with...
3
by: =?Utf-8?B?cm9nZXJfMjc=?= | last post by:
hey, I've seen this problem many times over the net, and now I'm one of them. simple code really. File.Move(RemoteFolder, MoveImportedFilesTo); where RemoteFolder =...
3
by: Gina_Marano | last post by:
Hey all, It appears that if I File.Move a large file 1GB from one network location to another location it is really slow. example. from: \\myserver\myfolder\a\largefile.txt to:...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.