Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.94/18: Рейтинг темы: голосов - 18, средняя оценка - 4.94
0 / 0 / 0
Регистрация: 29.08.2017
Сообщений: 25

Как добавить для StreamReader данные аутентификации?

29.08.2017, 16:39. Показов 3320. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Подскажите, как добавить для StreamReader данные аутентификации? Для файлов, которые находятся на других компьютерах.
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
29.08.2017, 16:39
Ответы с готовыми решениями:

Как добавить данные в файл для последующих действий с ними
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { ...

Как добавить добавить данные в базу данных посредством LINQ
Как добавить добавить данные в базу данных посредством LINQ to SQL Ошибка: Нарушение "PK_TICKER_MINUTE" ограничения PRIMARY...

Добавить поставщиков при создании аутентификации
Здравствуйте Я пытаюсь сделать аутентификацию пользователя. Я запустила aspnet_regsql.exe В базе SQL появились новые таблицы и...

1
Администратор
Эксперт .NET
 Аватар для OwenGlendower
18304 / 14228 / 5368
Регистрация: 17.03.2014
Сообщений: 28,901
Записей в блоге: 1
29.08.2017, 17:10
Лучший ответ Сообщение было отмечено J0rJ как решение

Решение

J0rJ, это делается путем имперсонификации перед обращением к файлу на другом компьютере
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
IntPtr token;
 
if (!NativeMethods.LogonUser(
    "userName",
    "domain",
    "Pa$$word",
    NativeMethods.LogonType.NewCredentials,
    NativeMethods.LogonProvider.Default,
    out token))
{
    throw new Win32Exception();
}
 
try
{
    IntPtr tokenDuplicate;
 
    if (!NativeMethods.DuplicateToken(
        token,
        NativeMethods.SecurityImpersonationLevel.Impersonation,
        out tokenDuplicate))
    {
        throw new Win32Exception();
    }
 
    try
    {
        using (WindowsImpersonationContext impersonationContext =
            new WindowsIdentity(tokenDuplicate).Impersonate())
        {
            // Работа с файлом
            // ...
 
            impersonationContext.Undo();
        }
    }
    finally
    {
        if (tokenDuplicate != IntPtr.Zero) NativeMethods.CloseHandle(tokenDuplicate);
    }
}
finally
{
    if (token != IntPtr.Zero) NativeMethods.CloseHandle(token);
}
NativeMethods
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
/// <summary>
/// Implements P/Invoke Interop calls to the operating system.
/// </summary>
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.
        /// </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.
        /// </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.
        /// This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
        /// </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);
}
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
29.08.2017, 17:10
Помогаю со студенческими работами здесь

Как прочитать данные из ячейки, и если она пуста добавить данные
Привет всем. У меня есть вот такой код: &lt;?php $arrqq = array($row-&gt;id); foreach($arrqq as $d =&gt; $s) { $imagetext =...

Как подправить Web.config для windows аутентификации?
В вебе и IIS я полный нуль ) Поэтому прошу помощи на форуме. Задача следующая - поднял RDS 2012R2 сервер, настроил прозрачную...

WCF: Запрос HTTP не разрешен для схемы аутентификации клиента "Ntlm". От сервера получен заголовок аутентификации "NTLM ."
Добрый день! Борюсь с WCF. Цель- подключиться и работать с вебсервисом от Битрикса. Подключиться удалось,методы все видятся. ...

Как запустить программу и передать логин и пароль для аутентификации (CheckPoint Endpoint Security)
Есть программа checkpoint endpoint Security, которую я хочу запускать через c# в качестве процесса, но при запуске нужно вводить логин и...

Как сделать свой “защитник” для аутентификации в Laravel с единственным токеном (вместо пары логин/пароль)?
Здравствуйте. Хочу сделать аутентификацию в Laravel обычным образом (не API, не REST) по единственному полю - рандомному (да вообще...


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

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Установка Qt Creator для C и C++: ставим среду, CMake и MinGW без фреймворка Qt
8Observer8 05.04.2026
Среду разработки Qt Creator можно установить без фреймворка Qt. Есть отдельный репозиторий для этой среды: https:/ / github. com/ qt-creator/ qt-creator, где можно скачать установщик, на вкладке Releases:. . .
AkelPad-скрипты, структуры, и немного лирики..
testuser2 05.04.2026
Такая программа, как AkelPad существует уже давно, и также давно существуют скрипты под нее. Тем не менее, прога живет, периодически что-то не спеша дополняется, улучшается. Что меня в первую очередь. . .
Отображение реквизитов в документе по условию и контроль их заполнения
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "ПланированиеСпецтехники", разработанного в конфигурации КА2. Данный документ берёт данные из другого нетипового документа. . .
Фото всей Земли с борта корабля Orion миссии Artemis II
kumehtar 04.04.2026
Это первое подобное фото сделанное человеком за 50 лет. Снимок называют новым вариантом легендарной фотографии «The Blue Marble» 1972 года, сделанной с борта корабля «Аполлон-17». Новое фото. . .
Вывод диалогового окна перед закрытием, если документ не проведён
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: реализовать программный контроль на предмет проведения документа. . .
Программный контроль заполнения реквизитов табличной части документа
Maks 02.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: 1. Реализовать контроль заполнения реквизита. . .
wmic не является внутренней или внешней командой
Maks 02.04.2026
Решение: DISM / Online / Add-Capability / CapabilityName:WMIC~~~~ Отсюда: https:/ / winitpro. ru/ index. php/ 2025/ 02/ 14/ komanda-wmic-ne-naydena/
Программная установка даты и запрет ее изменения
Maks 02.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: при создании документов установить период списания автоматически. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru