I want to copy file to networking drive.But it show error : C:\pdf.zip has denide (copytonetworkingdrive function).
So I want to change file ACL (copyfileto function).
Problem
1.) I can not access c:\pdf.zip
2.) I can not copy file c:\ to networking drive.
3.) I can not change file access control.
4.) I can not access \\networkingdrive\\blablabla$
( I has login by user via programming [look at logonuser function] )
I develop on windows 7 64bit, VS C# 2012, .Net Framework 4.0.
using Ionic.Zip;
using System.Security.Principal;
using System.Security.Permissions;
using System.Security.AccessControl;
using System.Management;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
My Code :
private static void copyfileto(string fin, string fout)
{
int i;
FileStream fsin, fsout;
*FileSecurity files = File.GetAccessControl(fin);*
WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
FileSystemAccessRule rule = new FileSystemAccessRule( self.Name, FileSystemRights.FullControl,AccessControlType.Allow);
AuthorizationRuleCollection acl = files.GetAccessRules(true,true, typeof(System.Security.Principal.NTAccount));
files.AddAccessRule( rule );
fsin = new FileStream( fin ,FileMode.Open);
fsout = new FileStream( fout ,FileMode.Create);
do
{ i = fsin.ReadByte() ;
if ( i != -1 ) fsout.WriteByte((byte) i );
} while ( i != -1);
fsin.Close();
fsout.Close();
}
private void copytonetworkdrive()
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
IntPtr hTokenLocal;
if (LogonUser(frm_main.myapp.gl_login_user_for_attachment.ToString(),
frm_main.myapp.gl_folder_attachment_server.ToString(),
frm_main.myapp.gl_pass_user_for_attachment.ToString(), LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, out hTokenLocal))
{
//if (hToken != IntPtr.Zero) CloseHandle(hToken);
//if (hTokenDuplicate != IntPtr.Zero) CloseHandle(hTokenDuplicate);
WindowsIdentity identity = new WindowsIdentity(hTokenLocal);
WindowsImpersonationContext context = identity.Impersonate();
copyfileto("C:\\Pdf.zip",frm_main.myapp.gl_folder_attachment_server.ToString() +#"ZIP\quotation\Pdf.zip");
}
}
In FileSecurity files = File.GetAccessControl(fin);
Error :
System.UnauthorizedAccessException was unhandled
HResult=-2147024891
Message=Attempted to perform an unauthorized operation.
Source=mscorlib
StackTrace:
at System.Security.AccessControl.Win32.GetSecurityInfo(ResourceType resourceType, String name, SafeHandle handle, AccessControlSections accessControlSections, RawSecurityDescriptor& resultSd)
at System.Security.AccessControl.NativeObjectSecurity.CreateInternal(ResourceType resourceType, Boolean isContainer, String name, SafeHandle handle, AccessControlSections includeSections, Boolean createByName, ExceptionFromErrorCode exceptionFromErrorCode, Object exceptionContext)
at System.Security.AccessControl.FileSystemSecurity..ctor(Boolean isContainer, String name, AccessControlSections includeSections, Boolean isDirectory)
...
Please Help and Thank.
Related
What I Want to achieve is to get file opened in Microsoft Word using C#. I have tried the following code and its working fine. But when i start Visual Studio 2019 with administrator privileges and try the same code, it doesn't work.
Here is my code
using System;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
namespace ConsoleApp2
{
class Program
{
#region OLE32 Methods
[DllImport("ole32.dll")]
static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
[DllImport("ole32.dll")]
static extern int CreateBindCtx(uint reserved, out IBindCtx ppbc);
#endregion
static void Main(string[] args)
{
try
{
Console.WriteLine($"File Name: {GetFileName()}");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine($"Error:{ex.Message}");
}
}
public static string GetFileName()
{
IRunningObjectTable runningObjectTable;
GetRunningObjectTable(0, out runningObjectTable);
dynamic objValue = GetRunningInstances("Word.Application", runningObjectTable);
if (objValue == null)
{
Console.WriteLine($"Word Application reference not found");
return string.Empty;
}
else
{
Console.WriteLine($"Word Application reference found");
}
dynamic propValue = objValue.ActiveWindow;
if (propValue == null) return string.Empty;
propValue = objValue.ActiveDocument;
if (propValue == null) return string.Empty;
string fileName = propValue.FullName ?? string.Empty;
return fileName;
}
static object GetRunningInstances(string progId, IRunningObjectTable Rot)
{
string clsId = null;
Type type = Type.GetTypeFromProgID(progId);
if (type != null)
clsId = type.GUID.ToString().ToUpper();
if (Rot == null)
return null;
// get enumerator for ROT entries
IEnumMoniker monikerEnumerator = null;
Rot.EnumRunning(out monikerEnumerator);
if (monikerEnumerator == null)
return null;
monikerEnumerator.Reset();
object instance = null;
IntPtr pNumFetched = new IntPtr();
IMoniker[] monikers = new IMoniker[1];
// go through all entries and identifies app instances
while (monikerEnumerator.Next(1, monikers, pNumFetched) == 0)
{
IBindCtx bindCtx;
CreateBindCtx(0, out bindCtx);
if (bindCtx == null)
continue;
string displayName;
monikers[0].GetDisplayName(bindCtx, null, out displayName);
if (displayName.ToUpper().IndexOf(clsId) > 0)
{
object ComObject;
Rot.GetObject(monikers[0], out ComObject);
if (ComObject == null)
continue;
instance = ComObject;
break;
}
}
return instance;
}
}
}
Environment I am using is
Visual Studio: 2019 v16.8.2
Target Framework:net5.0-windows
Project Type: Console
Steps to reproduce
Create a Console App Project and paste the above code in program.cs
open any file in Microsoft Word and run the app, it will display the path of the file opened in MS Word
Close Visual Studio, Open again with Administrative privileges and run the same project again, code will be unable to get path of the opened file.
Any Help will be appreciated.
Based on my test, I reproduced your problem. It is related to the GetRunningObjectTable method.
When we start the visual studio as the admin privileges, we only can see the processes that belongs to the admin. Of course, it also applies to standard users.
Therefore, when you use admin privileges for vs and standard privileges for ms-word, the parameter runningObjectTable will return null.
If you want to know more the details about the reason, you can refer to Understanding the Running Object Table.
Finally, if you want to get the correct result when you start vs with admin privileges, you also need start the word file with admin privileges. According to my test, it can get the correct result.
When I want to open an .ico file using Process.Start it throws an error System.ComponentModel.Win32Exception and this is because there is no default program to open that file. I need to show the window to select the default program instead of throwing exception. How can I do that?
private void btnOpenFile_Click(object sender, EventArgs e)
{
Process.Start(txtSavedAs.Text);
}
What you want to do is pinvoke the AssocQueryString API. Documentation here.
I use that API to get a command string associated with a shell verb. So, for example, if I use the .txt extension, it would return:
C:\Windows\system32\NOTEPAD.EXE %1
Now we know that shell knows what program to execute and how to pass in the command-line argument for that specific extension.
So, if there is a "Command" associated with that extension, it is safe to assume shell will know how to execute that type of file; Hence we should be able to use ShellExecute normally.
If there is no "Command" associated with that file extension, we will show the "openas" dialog allowing the user to pick the application they want to open the file.
Here is a class I put together to do that work:
AppAssociation.cs
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
public static class AppAssociation
{
private static class Win32Native
{
public const int ASSOCF_NONE = 0;
public const int ASSOCSTR_COMMAND = 1;
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode,
EntryPoint = "AssocQueryStringW")]
public static extern uint AssocQueryString(int flags, int str,
string pszAssoc, string pszExtra, StringBuilder pszOut, ref uint pcchOut);
}
public static Process StartProcessForFile(FileInfo file)
{
var command = GetCommandForFileExtention(file.Extension);
return Process.Start(new ProcessStartInfo()
{
WindowStyle = ProcessWindowStyle.Normal,
FileName = file.FullName,
Verb = string.IsNullOrEmpty(command) ? "openas" : null,
UseShellExecute = true,
ErrorDialog = true
});
}
private static string GetCommandForFileExtention(string ext)
{
// query length of the buffer we need
uint length = 0;
if (Win32Native.AssocQueryString(Win32Native.ASSOCF_NONE,
Win32Native.ASSOCSTR_COMMAND, ext, null, null, ref length) == 1)
{
// build the buffer
var sb = new StringBuilder((int)length);
// ask for the actual command string with the right-sized buffer
if (Win32Native.AssocQueryString(Win32Native.ASSOCF_NONE,
Win32Native.ASSOCSTR_COMMAND, ext, null, sb, ref length) == 0)
{
return sb.ToString();
}
}
return null;
}
}
You would call this like so:
AppAssociation.StartProcessForFile(new FileInfo(#"c:\MyFiles\TheFile.txt"));
I am new in C#, i am having a PowerShell Script to send files to multiple PC using IP address and username, there I am using new-PSDrive. I want to create the same program in C#.
I am not sure how to do that i went through some tutorials and tried it out but stuck with Windows Impersonate Class. It was written in the post that i followed that: _If we want to share file to a shared folder we can use File.Copy(destPath, SourcePath) but its not working.
This is the Code i am trying :
WindowsIdentity idnt = new WindowsIdentity("Administrator", "Test123!");
WindowsImpersonationContext context = idnt.Impersonate();
File.Copy(#"C:\\Sent.txt", #"\\192.xxx.xxx.xxx\\SharedFolder", true);
context.Undo();
An error Pop's up : The name provided is not a properly formed account name.
WindowsIdentity idnt = new WindowsIdentity("Administrator", "Test123!");
I don't know how to get proper name, i am trying this :
WindowsIdentity idnt = new WindowsIdentity(Username,Password);
I also trien this ("\192.xxx.xxx.xxx\WIN-9SMSBCR4V7B\SharedFolder",Password);
The Machine on which i want to copy files is running on Vmware on same machine and i am able to send using Powershell Script.
Any suggestion would be appreciated.
Found the Solution, Here's the complete code for sending files to a remote PC using its IP address, UserName and Password for machines which are not on same DOMAIN.
Here the Link which explains the use of correct LOGON PROVIDER
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.IO;
namespace File_Send_Test
{
class Program
{
[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 extern static bool CloseHandle(IntPtr handle);
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public static void Main(string[] args)
{
SafeTokenHandle safeTokenHandle;
try
{
string userName, domainName;
//domainName = Console.ReadLine();
domainName = ".";
Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
//provide username of remote machine.
userName = Console.ReadLine();
//provide password of remote machine.
Console.Write("Enter the password for {0}: ", userName);
//Here's the Catch
//LOGON32_PROVIDER_WinNT50 = 3; and LOGON32_LOGON_NewCredentials = 9;
const int LOGON32_PROVIDER_WinNT50 = 3;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_NewCredentials = 9;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
LOGON32_LOGON_NewCredentials, LOGON32_PROVIDER_WinNT50,
out safeTokenHandle);
Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
throw new System.ComponentModel.Win32Exception(ret);
}
using (safeTokenHandle)
{
Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);
// Check the identity.
Console.WriteLine("Before impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Use the token handle returned by LogonUser.
using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
{
using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
{
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
//File.Copy(Source File,DestinationFile);
File.Copy(#"C:\\Sent.txt", #"\\192.168.xxx.xxx\\Suji\\Sent.txt", true);
}
}
// Releasing the context object stops the impersonation
// Check the identity.
Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred. " + ex.Message);
}
Console.ReadLine();
}
}
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);
}
}
}
Hope this would help others.
You would have thought copying a file from one folder to a remote share (which needs a user name / password) would be simple ! But, it is not !
The following 2 links provide some options:
(1)
How to provide user name and password when connecting to a network share
The above links is about mapping a network drive first and then doing a file copy
(2) copy files with authentication in c#
This option is about using the WindowsIdentity class (as you have attempted). The above link gives a way to construct the object in a correct way
Both of the above options, in a way, are NOT pure .Net solutions. They call Win32 APIs directly.
Another option:
If you could have a mapped network connection created (outside of your application) first, then a simple file copy would work.
In that case the steps would be:
(1) Map a drive to the shared folder using an user name and password, using the net use command
net use Z: /delete
net use Z: \\server name\share name password /user:user name
(2) Run your copy program
File.Copy(sourceFileName, #"Z:\path\to\folder\filename");
(3) Remove the drive mapping
net use Z: /delete
I have a dotnet script which is for encryption and decryption. I have to pass the parameters for the setvalues function in installshield. How can I achieve this? Dotnet code is as follows. I have the assembly (.dll) file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Security;
using System.Xml;
using System.Collections.Specialized;
namespace EncryptionDecryption
{
public class EncrptionHelper
{
#region Member variables
static byte[] entropy = { 0, 8, 2, 3, 5 };
#endregion
#region Public Methods
public static void SetValue(string configFilePathName, string appSettingKey, string appSettingValue)
{
appSettingValue = EncryptString(ToSecureString(appSettingValue));
SetSetting(appSettingKey, appSettingValue, configFilePathName);
}
public static string GetValue(string configFilePathName, string appSettingKey)
{
string value = GetSetting(appSettingKey, configFilePathName);
value = ToInsecureString( DecryptString(value));
return value;
}
#endregion
#region Private Methods
private static bool SetSetting(string Key, string Value, string configFilePath)
{
bool result = false;
try
{
// System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(configFilePath);
// config.AppSettings.File = configFilePath;
// config.AppSettings.Settings[Key].Value = Value;
// config.Save(ConfigurationSaveMode.Modified);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(configFilePath);
xmlDoc.SelectSingleNode("//appSettings/add[#key='" + Key +"']").Attributes["value"].Value = Value;
xmlDoc.Save(configFilePath);
ConfigurationManager.RefreshSection("appSettings");
result = true;
}
finally
{ }
return result;
}
private static string GetSetting(string Key, string configFilePath)
{
string result = null;
try
{
XmlDocument appSettingsDoc = new XmlDocument();
appSettingsDoc.Load(configFilePath);
XmlNode node = appSettingsDoc.SelectSingleNode("//appSettings");
XmlElement value = (XmlElement)node.SelectSingleNode(string.Format("//add[#key='" + Key + "']"));
result = (value.GetAttribute("value").ToString());
}
finally
{ }
return result;
}
private static SecureString ToSecureString(string input)
{
SecureString secure = new SecureString();
foreach (char c in input)
{
secure.AppendChar(c);
}
secure.MakeReadOnly();
return secure;
}
private static string ToInsecureString(SecureString input)
{
string returnValue = string.Empty;
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
try
{
returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
}
return returnValue;
}
private static string EncryptString(System.Security.SecureString input)
{
byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)), entropy, System.Security.Cryptography.DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
private static SecureString DecryptString(string encryptedData)
{
try
{
byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
Convert.FromBase64String(encryptedData),
entropy,
System.Security.Cryptography.DataProtectionScope.CurrentUser);
return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
}
catch
{
return new SecureString();
}
}
#endregion
}
}
Update: Action start 14:31:36: Encryption.
MSI (c) (84:40) [14:31:36:525]: Invoking remote custom action. DLL: C:\Users\<username>\AppData\Local\Temp\MSIE259.tmp, Entrypoint: m1
InstallShield: Attempting to load through CLR 4 APIs...
InstallShield: Getting meta host...
InstallShield: Enumerating available runtimes...
InstallShield: Highest available runtime: v4.0.30319
InstallShield: Trying to use highest runtime...
InstallShield: Using highest version runtime...
InstallShield: Loading assembly Security.Encryption from resource 4097
InstallShield: Calling method with parameters [(System.String)C:\Program Files (x86)\<Installdir>\<configfilename>.config, (System.String)VWFPassword, (System.String)]
InstallShield: Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files (x86)\<Installdir>\<configfilename>.config'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at
System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.Load(String filename)
at Security.Encryption.EncrptionHelper.SetSetting(String appSettingKey, String appsettingValue, String configFilePathName)
at Security.Encryption.EncrptionHelper.SetValue(String configFilePathName, String appSettingKey, String appSettingValue)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at InstallShield.ClrHelper.CustomActionHelper.CallMethod(EntryPointInfo info)
at InstallShield.ClrHelper.CustomActionHelper.RunAction(UInt32 installHandle, Int32 entryNumber, Int64 instanceHandle)
InstallShield: Managed code threw an unhandled exception.
This is the error I receive after doing all that is mentioned in the screenshots below and doing some R&D. The directory mentioned "C:\Program Files (x86)\\.config" exists when the encryption custiom action is being called but it throws an exception.
Yes, it can be done with following steps:
1- write your required functionality in c# installer class (make sure your are using installer class)
2- Compile and add your dll into installshield (recomended create a separate component for this dll)
3- Select component view -> select above component and go to .Net settings section, set the ".Net Installer class" to true. Set the ".net installer class parameters"
Parameters are passed as key/value pair e.g
/targetDirectory="[INSTALLDIR]\"
All steps are same, just added screenshots.
Create a dll with an installer class and your encrypt/decrypt class.
Add dll and config file to component(above mentioned), if config file is already added to some other component then its fine. no need to add again.
I have added and retrieved INSTALLDIR variable as argument which is predefined. if you want to receive some input from user (from some custom textboxes) then you will need to define your own variables to store and pass values as arguments.
Creating dll with installer class and your requred logic for other task
Creating component and adding files
Mark the dll as installer class and pass arguments
Here goes installer class:
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Configuration.Install;
using System.Collections.Generic;
namespace EncryptionDecryption
{
[RunInstaller(true)]
public class InstallerClassDemo : Installer
{
private string installationDirectory=string.Empty;
private string testString=string.Empty ;
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
try
{
//For testing purpose only.. work only in debug mode when pdb files are deployed as well.
//Debugger.Break();
installationDirectory = Context.Parameters["INSTALLDIR"];
//I believe, the config file must be located in the installation directory if so, then use the following way to compute path
string configFilePath = Path.Combine(installationDirectory, "myConfigFile.config");
EncrptionHelper.SetValue(configFilePath, "testKey", "testValue");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
protected override void OnCommitted(System.Collections.IDictionary savedState)
{
base.OnCommitted(savedState);
}
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
}
}
}
I think installshield cannot (or need extra work) for read your assemblies, but you can run simple console application which consume your assemblies from installscript and passing parameter from installshield.
Create simple console application
Include console application on Support Files
Copy to installation folder or assemblies location, so console application can access your assemblies
Launch from installscript using launchappandwait
If consoleapp.exe not use anymore, just delete it.
I need to copy many folders from a server to another server. The servers are in different domains. Is tcp or ftp should be used? I am having the login credentials to access the server.
Is it possible to use something like
string sourceFile = #"ServerIP\C:\Users\Public\public\test.txt";
string destinationFile = #"Localhost\C:\Users\Public\private\test.txt";
// To move a file or folder to a new location:
System.IO.File.Copy(sourceFile, destinationFile);
You can grab the idea of doing it using the code snippet below. You can use LogonUser to impersonate a local group also not only domain accounts.
To copy all the contents (files) inside the Directory/Folder, obviously you can use the Directory class from inside System.IO namespace to get all the files information.
Code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
public class Form1
{
[DllImport("advapi32.DLL", SetLastError = true)]
public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
private void Button1_Click(System.Object sender, System.EventArgs e)
{
IntPtr admin_token = default(IntPtr);
WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
WindowsIdentity wid_admin = null;
WindowsImpersonationContext wic = null;
try {
MessageBox.Show("Copying file...");
if (LogonUser("Local Admin name", "Local computer name", "pwd", 9, 0, ref admin_token) != 0) {
wid_admin = new WindowsIdentity(admin_token);
wic = wid_admin.Impersonate();
System.IO.File.Copy("C:\\right.bmp", "\\\\157.60.113.28\\testnew\\right.bmp", true);
MessageBox.Show("Copy succeeded");
} else {
MessageBox.Show("Copy Failed");
}
} catch (System.Exception se) {
int ret = Marshal.GetLastWin32Error();
MessageBox.Show(ret.ToString(), "Error code: " + ret.ToString());
MessageBox.Show(se.Message);
} finally {
if (wic != null) {
wic.Undo();
}
}
}
}
Reference: Impersonate with Local Account
Is it possible to use something like ?
Shouldn't you find out that yourself ?
For
I need to copy many folders from a server to another server
To work with FTP, you will need to use System.Net.FtpWebRequest and System.Net.WebRequestMethods.Ftp,
see:
http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx,
http://msdn.microsoft.com/en-us/library/system.net.webrequestmethods.ftp.aspx.
Also a simple search on google gave many good ways of doing this, https://www.google.co.in/search?q=copy+files+from+one+server+to+another+using+asp.net
Please try one of these, and when you have problems when implementing them, should you come here and ask 'that' question. Not the other way round.