小编seb*_*ibu的帖子

C#和File.WriteAllText错误

我正在构建一个简单的C#应用​​程序,它必须在文件中写入用户输入.

我的第一个问题是我希望用户能够设置设置文件的路径,但我希望程序能够在以下启动时读取设置文件.

我的第二个问题是,如果我使用类似的东西:

    File.WriteAllText(@"C:\Users\Public\settings.settings", message);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

    System.Security.SecurityException: Request for the permission of type 
    'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, 
    Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at 
    System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& 
    stackMark, Boolean isPermSet)   at System.Security.CodeAccessPermission.Demand()
       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)
    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, 
    FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)

    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, 
    FileShare share, Int32 bufferSize, FileOptions …
Run Code Online (Sandbox Code Playgroud)

c# file-permissions

3
推荐指数
1
解决办法
1万
查看次数

在azure文件共享和blob之间移动文件

我必须在同一存储帐户上的共享和blob之间移动一些文件.经过一些谷歌搜索后我得到了这段代码:

CloudFileClient fileClient = account.CreateCloudFileClient();
CloudFileShare share = fileClient.GetShareReference("shareName");
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
CloudFileDirectory videoDirectory = rootDir.GetDirectoryReference(video.StoragePath);
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(video.StoragePath);
container.CreateIfNotExists();

foreach (var Files in videoDirectory.ListFilesAndDirectories())
{
    var arr = Files.Uri.ToString().Split('/');
    string strFileName = arr[arr.Length - 1];
    CloudFile sourceFile = videoDirectory.GetFileReference(strFileName);
    string fileSas = sourceFile.GetSharedAccessSignature(new SharedAccessFilePolicy()
    {
        Permissions = SharedAccessFilePermissions.Read,
        SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24)
    });

    Uri fileSasUri = new Uri(sourceFile.StorageUri.PrimaryUri.ToString() + fileSas);

    CloudBlockBlob blockBlob = container.GetBlockBlobReference(strFileName);
    blockBlob.StartCopyAsync(fileSasUri).Wait();    //copy the file to blob storage and wait for …
Run Code Online (Sandbox Code Playgroud)

azure azure-storage-blobs azure-files azure-storage-files

3
推荐指数
1
解决办法
3262
查看次数

可为空的通用扩展方法

我想编写一个通用扩展方法,如果没有值则抛出错误。所以我想要这样的东西:

public static T GetValueOrThrow(this T? candidate) where T : class
        {
            if (candidate.HasValue == false)
            {
                throw new ArgumentNullException(nameof(candidate));
            }

            return candidate.Value;
        }
Run Code Online (Sandbox Code Playgroud)
  1. C# 无法识别 T:找不到类型或命名空间名称“T”
  2. C# 无法识别 where:非泛型声明中不允许使用约束

知道这是否有效吗?我错过了什么?

我还想出了:

public static T GetValueOrThrow<T>(this T? candidate) where T : class
        {
            if (candidate.HasValue == false)
            {
                throw new ArgumentNullException(nameof(candidate));
            }

            return candidate.Value;
        }
Run Code Online (Sandbox Code Playgroud)

现在 C# 抱怨候选者:类型 T 必须是不可为 null 的值类型才能将其用作泛型类型或方法 Nullable 中的参数 T

这与比较无关。

c# extension-methods nullable

3
推荐指数
1
解决办法
615
查看次数

WCF使用参数发出POST请求

我有一个暴露休息端点的wcf服务.我想用fiddler来测试它.我有这样的方法:

 [WebInvoke(Method = "POST", UriTemplate = "EditContact", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    string EditContact(string idContact, Contact Contact);
Run Code Online (Sandbox Code Playgroud)

我输入:

POST http://192.168.1.31/ContactLibrary2.0/Service.svc/rest/DeleteContact HTTP/1.1

User-Agent: Fiddler
Host: 192.168.1.31
Content-Type : application/json; Charset=UTF-8

{
"idContact":"67697",
"firstName":"6767",
"lastName":"afdgsg",
"email":"dfghdfdb",
"age":"120",
"street":"sdf",
"city":"dfghgfhjhdfgsdv",
"country":"sdfsd"
}
Run Code Online (Sandbox Code Playgroud)

从我的项目中可以看到更多代码:HERE

我收到http 400错误(错误的请求错误).想法?

wcf post json fiddler

2
推荐指数
1
解决办法
6189
查看次数

在ORDER BY中首先放置一行

我想更改select产生的记录顺序.

我希望某个记录成为我列表中的第一个记录,之后是其他记录.

t-sql sql-server

2
推荐指数
1
解决办法
205
查看次数

引导颜色选择器更大

有什么方法可以使自举颜色选择器框更大?我查看了它的css,但找不到设置盒子高度和重量的位置。

我正在使用此颜色选择器:Stefan Petre的Bootstrap Colorpicker

html color-picker twitter-bootstrap twitter-bootstrap-2

2
推荐指数
1
解决办法
4695
查看次数

Net Core使用HttpClient测试方法

我有一个使用 执行请求的服务方法HttpClient。服务类构造函数IHttpClientFactory使用以下代码注入并创建客户端:

_httpClient = httpClientFactory.CreateClient(url);
Run Code Online (Sandbox Code Playgroud)

在我的测试构造函数中,我试图模拟PostAsync方法响应。

public MyServiceUnitTests()
    {
        _HttpClientMock = new Mock<IHttpClientFactory>();
        var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
        mockHttpMessageHandler.Protected()
            .Setup<Task<HttpResponseMessage>>("PostAsync", ItExpr.IsAny<string>(), ItExpr.IsAny<HttpContent>())
            .ReturnsAsync(new HttpResponseMessage{ StatusCode = HttpStatusCode.OK });
        var httpClient = new HttpClient(mockHttpMessageHandler.Object);
        _HttpClientMock.Setup(x => x.CreateClient(It.IsAny<string>())).Returns(httpClient);

        _Service = new MyService(_HttpClientMock.Object);
    }
Run Code Online (Sandbox Code Playgroud)

设置mockHttpMessageHandler 时出现以下错误:System.ArgumentException: 'No protected method HttpMessageHandler.PostAsync found whose signature is compatible with the provided arguments (string, HttpContent).'

我究竟做错了什么?

c# moq httpclient asp.net-core

1
推荐指数
1
解决办法
1678
查看次数

从数据库接收null时出错

当我在我的数据库上执行此命令时,我有时会收到result = null.我想在这种情况下进入"其他"部分,但我收到了

mscorlib.dll中发生了未处理的"System.FormatException"类型异常.附加信息:输入字符串的格式不正确.

DB database = new DB();
            int reservedSeats = 0;
            using (database.sqlConnection)
            {
                database.sqlConnection.Open();
                string command = "select SUM(nrLocuri) as result from Rezervari where idRand = @idRand and idShow=@idShow";
                using (SqlCommand cmd = new SqlCommand(command, database.sqlConnection))
                {
                    cmd.Parameters.Add("@idRand", SqlDbType.Int).Value = idRand;
                    cmd.Parameters.Add("@idShow", SqlDbType.Int).Value = idShow;
                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        if (dr.Read())
                            if (dr["result"].ToString() != null)
                                reservedSeats = Convert.ToInt32(dr["result"].ToString());
                            else
                                return totalSeats;
                    }
                }
            }
            return totalSeats-reservedSeats; 
Run Code Online (Sandbox Code Playgroud)

c# sql-server

0
推荐指数
1
解决办法
94
查看次数