C# 多线程 11-更多信息 02-在通常的应用程序中使用 WinRT
🏷️ 《C# 多线程》
实现方式
从解决方案中卸载项目
右键单击被卸载的项目,选择【编辑 projectname.csproj】
在
<TargetFrameworkVersion>
元素下添加如下 XML 代码xml<TragetPlatformVersion>10.0</TragetPlatformVersion>
保存工程文件,并再次右键单击项目,选择【重新加载项目】
添加如下引用
C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.15063.0\Windows.winmd
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
示例代码
csharp
class Program
{
static void Main(string[] args)
{
var t = AsynchronousProcessing();
t.GetAwaiter().GetResult();
Console.WriteLine();
Console.WriteLine("Press ENTER to exit.");
Console.ReadLine();
}
async static Task AsynchronousProcessing()
{
StorageFolder folder = KnownFolders.DocumentsLibrary;
if (await folder.DoesFileExistAsync("test.txt"))
{
var fileToDelete = await folder.GetFileAsync("test.txt");
await fileToDelete.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
var file = await folder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
using (var writer = new StreamWriter(stream.AsStreamForWrite()))
{
await writer.WriteLineAsync("Test content");
await writer.FlushAsync();
}
using (var stream = await file.OpenAsync(FileAccessMode.Read))
using (var reader = new StreamReader(stream.AsStreamForRead()))
{
string content = await reader.ReadToEndAsync();
Console.WriteLine(content);
}
Console.WriteLine("Enumerating Folder Structure:");
var itemsList = await folder.GetItemsAsync();
foreach (var item in itemsList)
{
if (item is StorageFile)
{
Console.WriteLine("{0} folder", item.Name);
}
else
{
Console.WriteLine(item.Name);
}
}
}
}
static class Extensions
{
public static async Task<bool> DoesFileExistAsync(this StorageFolder folder, string fileName)
{
try
{
await folder.GetFileAsync(fileName);
return true;
}
catch (FileNotFoundException)
{
return false;
}
}
}
运行结果
txt
Test content
Enumerating Folder Structure:
Diablo III
FeedbackHub
IISExpress
My Web Sites
QQEIM Files
Tencent Files
Visual Studio 2017
WeChat Files
test.txt folder
Press ENTER to exit.
工作原理
这里使用了一种很取巧的方式在普通的.NET 控制台程序中使用 WinRT API。
不幸的是,该场景并不适用所有的 API,但仍可支持运动传感器、GPS 定位服务等。