С Новым годом! Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.61/18: Рейтинг темы: голосов - 18, средняя оценка - 4.61
0 / 0 / 0
Регистрация: 10.02.2015
Сообщений: 42
.NET 4.x

Скопировать файл с сети на свой диск

31.01.2016, 10:49. Показов 3696. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Пытаюсь копировать файл с сетевого ресурса на свой диск, не получается.
SecurityException: "Указанное имя не является корректным именем пользователя."

Что не так?

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Principal;
using System.IO;
 
namespace network_downloader
{
    class Program
    {
 
       static void Main(string[] args)
        {
           string username = @"domain\tstusr"; // Нужно чтобы соединялось и через домен и без.
           string password = @"qwerty123$";
           string network_file_path = @"\\192.168.1.101\c$\test.txt";
           string local_file_path = @"c:\test.txt";
           AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
           WindowsIdentity idnt = new WindowsIdentity(username, password);
           WindowsImpersonationContext context = idnt.Impersonate();
           File.Copy(network_file_path, local_file_path, true);
           context.Undo();
        }
    }
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
31.01.2016, 10:49
Ответы с готовыми решениями:

Скопировать папку по сети со всем содержимым (XCOPY и сетевой диск)
Скопировать папку по сети, со всем содержимым XCOPY, и сетевой диск Начальный код Копирование обычное.cmd // файл в кодировке...

Скопировать файл из памяти на диск
Я использую инжекцию dll в чужой процесс и перехватываю функцию CreateFileA Далее мне нужно добавить свой обработчик,чтобы все файлы...

Не получается скопировать файл 4.5 Гб на внешний жесткий диск
Говорит, недостаточно места, - а на самом деле 130 Гб свободны. При этом, формат диска и так nfts, fat32 там вообще не предусмотрен. Винда...

1
Администратор
Эксперт .NET
 Аватар для OwenGlendower
18245 / 14169 / 5366
Регистрация: 17.03.2014
Сообщений: 28,848
Записей в блоге: 1
06.02.2016, 22:06
kloopa, попробуй вот так:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
IntPtr token;
if (NativeMethods.LogonUser("userName", "domain", "Pa$$word", NativeMethods.LogonType.NewCredentials, NativeMethods.LogonProvider.Default, out token))
{   
    try
    {
        IntPtr tokenDuplicate;
 
        if (NativeMethods.DuplicateToken(token, NativeMethods.SecurityImpersonationLevel.Impersonation, out tokenDuplicate))
        {
            try
            {
                using (WindowsImpersonationContext impersonationContext = new WindowsIdentity(tokenDuplicate).Impersonate())
                {
                    string network_file_path = @"\\192.168.1.101\c$\test.txt";
                    string local_file_path = @"c:\test.txt";
                    File.Copy(network_file_path, local_file_path, true);
           
                    impersonationContext.Undo();
                }
            }
            finally
            {
                if (tokenDuplicate != IntPtr.Zero) NativeMethods.CloseHandle(tokenDuplicate);
            }
        }
    }
    finally
    {
        if (token != IntPtr.Zero) NativeMethods.CloseHandle(token)
    }
}
NativeMethods class
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
internal static class NativeMethods
{
    /// <summary>
    /// The type of logon operation to perform.
    /// </summary>
    internal enum LogonType : int
    {
        /// <summary>
        /// This logon type is intended for users who will be interactively
        /// using the computer, such as a user being logged on by a
        /// terminal server, remote shell, or similar process.
        /// This logon type has the additional expense of caching logon
        /// information for disconnected operations; therefore, it is
        /// inappropriate for some client/server applications, such as a
        /// mail server.
        /// </summary>
        Interactive = 2,
 
        /// <summary>
        /// This logon type is intended for high performance servers to
        /// authenticate plaintext passwords.
        /// The LogonUser function does not cache credentials for this
        /// logon type.
        /// </summary>
        Network = 3,
 
        /// <summary>
        /// This logon type is intended for batch servers, where processes
        /// may be executing on behalf of a user without their direct
        /// intervention.  This type is also for higher performance servers
        /// that process many plaintext authentication attempts at a time,
        /// such as mail or Web servers.
        /// The LogonUser function does not cache credentials for this
        /// logon type.
        /// </summary>
        Batch = 4,
 
        /// <summary>
        /// Indicates a service-type logon.  The account provided must have
        /// the service privilege enabled.
        /// </summary>
        Service = 5,
 
        /// <summary>
        /// This logon type is for GINA DLLs that log on users who will be
        /// interactively using the computer.
        /// This logon type can generate a unique audit record that shows
        /// when the workstation was unlocked.
        /// </summary>
        Unlock = 7,
 
        /// <summary>
        /// This logon type preserves the name and password in the
        /// authentication package, which allows the server to make
        /// connections to other network servers while impersonating the
        /// client.  A server can accept plaintext credentials from a
        /// client, call LogonUser, verify that the user can access the
        /// system across the network, and still communicate with other
        /// servers.
        /// NOTE: Windows NT:  This value is not supported.
        /// </summary>
        NetworkCleartext = 8,
 
        /// <summary>
        /// This logon type allows the caller to clone its current token
        /// and specify new credentials for outbound connections.  The new
        /// logon session has the same local identifier but uses different
        /// credentials for other network connections.
        /// NOTE: This logon type is supported only by the
        /// LOGON32_PROVIDER_WINNT50 logon provider.
        /// NOTE: Windows NT:  This value is not supported.
        /// </summary>
        NewCredentials = 9
    }
 
    /// <summary>
    /// Specifies the logon provider.
    /// </summary>
    internal enum LogonProvider : int
    {
        /// <summary>
        /// Use the standard logon provider for the system.
        /// The default security provider is negotiate, unless you pass
        /// NULL for the domain name and the user name is not in UPN format.
        /// In this case, the default provider is NTLM.
        /// NOTE: Windows 2000/NT:   The default security provider is NTLM.
        /// </summary>
        Default = 0,
 
        /// <summary>
        /// Use this provider if you'll be authenticating against a Windows
        /// NT 3.51 domain controller (uses the NT 3.51 logon provider).
        /// </summary>
        WinNT35 = 1,
 
        /// <summary>
        /// Use the NTLM logon provider.
        /// </summary>
        WinNT40 = 2,
 
        /// <summary>
        /// Use the negotiate logon provider.
        /// </summary>
        WinNT50 = 3
    }
 
    /// <summary>
    /// The type of logon operation to perform.
    /// </summary>
    internal enum SecurityImpersonationLevel : int
    {
        /// <summary>
        /// The server process cannot obtain identification information
        /// about the client, and it cannot impersonate the client.  It is
        /// defined with no value given, and thus, by ANSI C rules,
        /// defaults to a value of zero.
        /// </summary>
        Anonymous = 0,
 
        /// <summary>
        /// The server process can obtain information about the client,
        /// such as security identifiers and privileges, but it cannot
        /// impersonate the client.  This is useful for servers that export
        /// their own objects, for example, database products that export
        /// tables and views.  Using the retrieved client-security
        /// information, the server can make access-validation decisions
        /// without being able to use other services that are using the
        /// client's security context.
        /// </summary>
        Identification = 1,
 
        /// <summary>
        /// The server process can impersonate the client's security
        /// context on its local system.  The server cannot impersonate the
        /// client on remote systems.
        /// </summary>
        Impersonation = 2,
 
        /// <summary>
        /// The server process can impersonate the client's security
        /// context on remote systems.
        /// NOTE: Windows NT:  This impersonation level is not supported.
        /// </summary>
        Delegation = 3
    }
 
    /// <summary>
    /// Logs on the user.
    /// </summary>
    /// <param name="userName">Name of the user.</param>
    /// <param name="domain">The domain.</param>
    /// <param name="password">The password.</param>
    /// <param name="logonType">Type of the logon.</param>
    /// <param name="logonProvider">The logon provider.</param>
    /// <param name="token">The token.</param>
    /// <returns>True if the function succeeds, false if the function fails.
    /// To get extended error information, call GetLastError.</returns>
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool LogonUser(
        string userName,
        string domain,
        string password,
        LogonType logonType,
        LogonProvider logonProvider,
        out IntPtr token);
 
    /// <summary>
    /// Duplicates the token.
    /// </summary>
    /// <param name="existingTokenHandle">The existing token
    /// handle.</param>
    /// <param name="securityImpersonationLevel">The security impersonation
    /// level.</param>
    /// <param name="duplicateTokenHandle">The duplicate token
    /// handle.</param>
    /// <returns>True if the function succeeds, false if the function fails.
    /// To get extended error information, call GetLastError.</returns>
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool DuplicateToken(
        IntPtr existingTokenHandle,
        SecurityImpersonationLevel securityImpersonationLevel,
        out IntPtr duplicateTokenHandle);
 
    /// <summary>
    /// Closes the handle.
    /// </summary>
    /// <param name="handle">The handle.</param>
    /// <returns>True if the function succeeds, false if the function fails.
    /// To get extended error information, call GetLastError.</returns>
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool CloseHandle(IntPtr handle);
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
06.02.2016, 22:06
Помогаю со студенческими работами здесь

Как скопировать файл на диск из ресурсов приложения?
Всем добрый вечер! Очень срочная проблема. У меня в солюшне несколько проектов. В основном проекте есть папка с картинками -...

Как скопировать файл к себе по сети?
Добрый убунту server стоит как скопировать файл к себе на ПК по сети, пробовал подключиться по wincsp пишет типо нет прав?!

Как файл из ресурсов программы скопировать на диск в нужную папку?
{$resource 'background.png'}как скопировать например на диск C в папку backgrounds я пробовал так...

Как скопировать файл на системный диск без запуска от имени администратора?
Я нашел функцию, которая копирует файл: CopyFile(L&quot;D:\\testfile.txt&quot;, L&quot;C:\\2.txt&quot;, false); Но, при запуске .ехе файла проекта не от...

Как сделать доступным программе свой файл, но в сети
Здравствуйте все! У меня такая проблема. Сделал 'прогу'. Разрешил доступ по локальной сети к папке на моем компе и к корневой папке в...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Модель микоризы: классовый агентный подход
anaschu 02.01.2026
Раньше это было два гриба и бактерия. Теперь три гриба, растение. И на уровне агентов добавится между грибами или бактериями взаимодействий. До того я пробовал подход через многомерные массивы,. . .
Учёным и волонтёрам проекта «Einstein@home» удалось обнаружить четыре гамма-лучевых пульсара в джете Млечного Пути
Programma_Boinc 01.01.2026
Учёным и волонтёрам проекта «Einstein@home» удалось обнаружить четыре гамма-лучевых пульсара в джете Млечного Пути Сочетание глобально распределённой вычислительной мощности и инновационных. . .
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru