Создание ftp сайта программно - PullRequest
1 голос
/ 11 ноября 2010

Я написал код для создания нового сайта в ftp.но это дает исключение ком.код прикреплен для справки.

Исключением являются

System.Runtime.InteropServices.COMException was unhandled
  Message="Filename: \r\nError: Unrecognized element 'ftpServer'\r\n\r\n"
  Source=""
  ErrorCode=-2147023483
  StackTrace:
       at Microsoft.Web.Administration.Interop.IAppHostElement.GetElementByName(String bstrSubName)
       at Microsoft.Web.Administration.ConfigurationElement.GetChildElement(String elementName)
       at WindowsFormsTest.Form2.CreateFTPSite(String serverName, String siteName, String siteID) in D:\My Projects\WindowsFormsTest\WindowsFormsTest\Form2.cs:line 48
       at WindowsFormsTest.Form2.button1_Click(Object sender, EventArgs e) in D:\My Projects\WindowsFormsTest\WindowsFormsTest\Form2.cs:line 25
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at WindowsFormsTest.Program.Main() in D:\My Projects\WindowsFormsTest\WindowsFormsTest\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

код для создания ftp сайта:

using(ServerManager serverManager = new ServerManager()) { 
        Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();

        ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");

        ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();

        ConfigurationElement siteElement = sitesCollection.CreateElement("site");
        siteElement["name"] = @"eMentorftp";

        ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");

        ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
        bindingElement["protocol"] = @"ftp";
        bindingElement["bindingInformation"] = @"*:21:";
        bindingsCollection.Add(bindingElement);

        ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer");

        ConfigurationElement securityElement = ftpServerElement.GetChildElement("security");

        ConfigurationElement sslElement = securityElement.GetChildElement("ssl");
        sslElement["serverCertHash"] = @"53FC3C74A1978C734751AB7A14A3E48F70A58A84";
        sslElement["controlChannelPolicy"] = @"SslRequire";
        sslElement["dataChannelPolicy"] = @"SslRequire";

        ConfigurationElement authenticationElement = securityElement.GetChildElement("authentication");

        ConfigurationElement basicAuthenticationElement = authenticationElement.GetChildElement("basicAuthentication");
        basicAuthenticationElement["enabled"] = true;

        ConfigurationElementCollection siteCollection = siteElement.GetCollection();

        ConfigurationElement applicationElement = siteCollection.CreateElement("application");
        applicationElement["path"] = @"/";

        ConfigurationElementCollection applicationCollection = applicationElement.GetCollection();

        ConfigurationElement virtualDirectoryElement = applicationCollection.CreateElement("virtualDirectory");
        virtualDirectoryElement["path"] = @"/";
        virtualDirectoryElement["physicalPath"] = @"D:\Ftp";
        applicationCollection.Add(virtualDirectoryElement);
        siteCollection.Add(applicationElement);
        sitesCollection.Add(siteElement);

        serverManager.CommitChanges();

1 Ответ

5 голосов
/ 14 января 2011

Вы можете сказать, что ваша ошибка из исключения.Посмотрите на первую строку в трассировке стека исключений:

System.Runtime.InteropServices.COMException is nothandled Message = "Имя файла: \ r \ nError: Нераспознанный элемент 'ftpServer' \ r \ n \ r\ n "Source =" "ErrorCode = -2147023483

Прежде всего, мы видим" Нераспознанный элемент 'ftpserver' "- который должен многое рассказать нам о том, что произошло, когда мы смотрим на ваш код.Но в дополнение к этому нам предоставляется код ошибки, который точно сообщает нам, почему возникло исключение COMException.Если мы расшифруем код ошибки в целое число без знака (шестнадцатеричное), мы получим:

0x80070585

Это соответствует коду ошибки:

  • 8: Ошибка
  • 7: Win32
  • 585: (десятичный 1413): неверный индекс (ERROR_INVALID_INDEX)

Для получения дополнительной информации о кодах ошибок см. HRESULT и Win32 коды ошибок .

Итак, мы сгенерировали исключение COMExec, потому что мы использовали недопустимый индекс.И мы получаем «нераспознанный элемент« ftpServer »» в сообщении об исключении.Просматривая свой код, вы создаете новый элемент ConfigurationElement siteElement, сообщая sitesCollection добавить новый элемент с именем «site»:

Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();
ConfigurationElement siteElement = sitesCollection.CreateElement("site");

Затем вы создаете имя для сайта и создаете привязки в привязках сайта.collection:

siteElement["name"] = @"eMentorftp";
ConfigurationElementCollection bindingsCollection = siteElement.GetCollection("bindings");
ConfigurationElement bindingElement = bindingsCollection.CreateElement("binding");
bindingElement["protocol"] = @"ftp";
bindingElement["bindingInformation"] = @"*:21:";
bindingsCollection.Add(bindingElement);

К сожалению, вы затем пытаетесь получить дочерний элемент сайта, используя имя «ftpServer»:

ConfigurationElement ftpServerElement = siteElement.GetChildElement("ftpServer"); 

Но элемент ConfigurationElement siteElement, который был только что создан- не имеет ребенка с именем ftpServer!Таким образом, мы получаем неверный индекс и генерируем исключение.Вы хотели создать дочерний элемент в этой строке кода?

Кроме того, я представляю, что это исключение COMExec из-за взаимодействия интерфейса .NET с соответствующими COM-объектами IIS7.Не быть экспертом (вообще) в пространстве имен Microsoft.Web, это всего лишь предположение.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...