C# - The type or namespace name 'Security'

2019-02-21 03:40发布

问题:

I'm trying to run this script but the IDE gives me the error mentioned in the title, specifically on line 6. I'm using Xamarin Studio 6.3 with .NET 4.5 as my target framework. I chose a .NET Console Project as my solution for running this program. I've tried adding System.Security as an assembly reference, still received the error. Then I added every .NET 4.5-related reference to my project just in case, issue persisted. Here is the script I'm trying to run:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Credentials;

namespace PasswordVaultTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a handle to the Widnows Password vault
            Windows.Security.Credentials.PasswordVault vault = new PasswordVault();
            // Retrieve all the credentials from the vault
            IReadOnlyList<PasswordCredential> credentials = vault.RetrieveAll();
            // The list returned is an IReadOnlyList, so there is no enumerator.
            // No problem, we'll just see how many credentials there are and do it the
            // old fashioned way
            for (int i = 0; i < credentials.Count; i++)
            {
                // Obtain the credential
                PasswordCredential cred = credentials.ElementAt(i);
                // "Fill in the password" (I wish I knew more about what this was doing)
                cred.RetrievePassword();
                // Print the result
                Console.WriteLine(cred.Resource + ':' + cred.UserName + ':' + cred.Password);
            }
            Console.ReadKey();
        }
    }
}

回答1:

The Reference you need to the Windows namespace is not visual by default. Per Alex's answer at the below post:

In the desktop projects the Core tab doesn’t appear by default. You can add the Windows Runtime by opening the shortcut menu for the project node, choosing Unload Project, adding the following snippet, and re-opening the project (on the project node choose Reload Project). When you invoke the Reference Manager dialog box, the Core tab appears.

<PropertyGroup>
    <TargetPlatformVersion>8.0</TargetPlatformVersion>
</PropertyGroup>

Make sure to check the Windows box on this tab. You should then be able to use WinRT elements.

I have done this and your code statement above compiles without error. Here is a link to the original answer:

How to access the stored credentials (Password Value?)