Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8192553
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T04:12:26+00:00 2026-06-07T04:12:26+00:00

I tried to upload file to a network path with following codes for silverlight

  • 0

I tried to upload file to a network path with following codes for silverlight app:

public void ProcessRequest (HttpContext context) 
{
  //.....
  using (FileStream fs = File.Create(@"\\Server\Folder\" + filename))            
 {
   byte[] buffer = new byte[4096];
   int bytesRead;
   while ((bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length)) != 0)
   {
      fs.Write(buffer, 0, bytesRead);
   }
 }
}

It’s working fine when I run it in debug mode with VS built-in web server. At SL side, I call this handler with url like:

UriBuilder ub = new UriBuilder("http://localhost:38700/FileUpload.ashx");

Then I publish this app to local IIS and change the url to http://localhost/Mysite/FileUpload.ashx

then run the app again. It won’t work anymore, but no error.

I guess it is because different credential to call File.Create. So I want to use specific credential in handler to put file to the destination.

How to use a credential for File.Create?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T04:12:27+00:00Added an answer on June 7, 2026 at 4:12 am

    I believe you will need to impersonate a user. The code below should do it. Essentially, you gather the domain, user, and password and instantiate the ImpersonationMgr class. Then call the BeginImpersonation method. After that call the corresponding WriteFile method you wish. The WriteFile method will assert if impersonation is enabled. You can follow similar patterns for other file methods such as delete and move.

    public class ImpersonationMgr : IDisposable
    
      [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
      public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType,
                                          int dwLogonProvider, out SafeTokenHandle phToken);
    
      [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
      public static extern bool CloseHandle(IntPtr handle);
    
      private const int LOGON32_PROVIDER_DEFAULT = 0;
      private const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
    
      private readonly string userName = string.Empty;
      private readonly string domainName = string.Empty;
      private readonly string password = string.Empty;
    
      private SafeTokenHandle safeTokenHandle = null;
      private WindowsImpersonationContext impersonatedUser = null;
    
      public ImpersonationMgr(string userName, string domainName, string password)
      {
         this.userName = userName;
         this.domainName = domainName;
         this.password = password;
      }
    
      public void BeginImpersonation()
      {
         bool returnValue = LogonUser(userName, domainName, password, LOGON32_LOGON_NEW_CREDENTIALS,
                                      LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);
         if (returnValue == false)
         {
            int ret = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(ret);
         }
    
         impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle());
      }
    
      private void AssertImpersonationIsEnabled()
      {
         if(safeTokenHandle == null || impersonatedUser == null)
         {
            throw new UnauthorizedAccessException("You must call the BeginImpersonation method before attempting file write access.");
         }
      }
    
      public void WriteFile(string pathToFile, string fileContents)
      {
         AssertImpersonationIsEnabled();
         using (FileStream fileStream = File.Open(pathToFile, FileMode.CreateNew))
         {
            using (StreamWriter fileWriter = new StreamWriter(fileStream))
            {
               fileWriter.Write(fileContents);
            }
         }
      }
    
      public void WriteFile(string pathToFile, byte[] fileContents)
      {
         AssertImpersonationIsEnabled();
         using (FileStream fileStream = new FileStream(pathToFile, FileMode.Create))
         {
            fileStream .Write(fileContents, 0, fileContents.Length);
            fileStream .Flush();          
         }
      }
    
      public void Dispose()
      {
         Dispose(true);
         GC.SuppressFinalize(this);
      }
    }
    

    UPDATE

       public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
       {
          private SafeTokenHandle()
             : base(true)
          {
          }
    
    
          [DllImport("kernel32.dll")]
          [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
          [SuppressUnmanagedCodeSecurity]
          [return: MarshalAs(UnmanagedType.Bool)]
          private static extern bool CloseHandle(IntPtr handle);
    
          protected override bool ReleaseHandle()
          {
             return CloseHandle(handle);
          }
       }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Following this thread, I tried to upload a file on the server. If I
I've tried to upload file using a form without an entity class. No luck
I tried to upload a vcard file using codeigniter. But It's not allowed to
I want to find device network upload speed and latency, I tried FTP file
I have tries to upload the file using rich:fileupload componenet.When i tried to upload
I tried to upload a file to my jersey server, but there is an
I have tried to upload image using FileTransfer.upload in phonegap api.But I am getting
How can I upload files to server using JSP/Servlet? I tried this: <form action="upload"
I have tried to upload .htaccess file on server, ftp gave me critical file
I'm using Kohana3 framework and Uploadify plugin for ajax file upload. When I try

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.