【发布时间】:2021-06-25 14:41:58
【问题描述】:
我尝试使用 Windows 应用程序文档来读取 UWP 上的临时文件(读写)。但是我无法使用以下链接中的示例中的文档使其工作
Documentation 在这个部分:
async void WriteTimestamp()
{
Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter =
new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
StorageFile sampleFile = await temporaryFolder.CreateFileAsync("dataFile.txt",
CreateCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTimeOffset.Now));
}
但很快我就遇到了“临时文件夹”的问题。据说在当前上下文中不存在。所以... 我尝试:(1)添加“使用Windows.Storage;”不工作... (2) 对外声明:
public Windows.Storage.StorageFolder temporaryFolder { get; set; }
这次代码说没有错误,但是当我启动程序时它停止了。 " '对象引用未设置为对象的实例。' App12UIWindows.Page2.temporaryFolder.get 返回 null。”
所以我从这里 (stackoverflow) 尝试了一个解决方案,它奏效了。关联: Alternative Solution
我的问题是:为什么会出错?文件是正确的还是别的什么? 还是我在错误的地方搜索?我的代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Collections.ObjectModel;
using Windows.Storage;
using System.Threading.Tasks;
namespace App12UIWindows
{
/// <summary>
/// </summary>
public sealed partial class Page2 : Page
{
public Page2()
{
this.InitializeComponent();
SaveTempFunc();
readMyFileTemp();
}
public Windows.Storage.StorageFolder temporaryFolder { get; set; }
async void SaveTempFunc()
{
StorageFile salvandoClientesT = await
temporaryFolder.CreateFileAsync("textOf_Information.txt") ;
await FileIO.WriteTextAsync(salvandoClientesT,"test .. just like that... and
anothers words to a file");
}
//Fim salvando memória temporária
//Lendo na memória temporária arquivo de texto
async void readMyFileTemp()
{
try
{
StorageFile lendoTextoSalvo = await
temporaryFolder.GetFileAsync("textOf_Information.txt");
String timestamp = await FileIO.ReadTextAsync(lendoTextoSalvo);
}
catch (Exception)
{
}
}
}
}
抱歉英语不好:)
【问题讨论】:
标签: c# uwp documentation