【问题标题】:Create text file in a given folder在给定文件夹中创建文本文件
【发布时间】:2015-01-11 20:08:08
【问题描述】:

我正在使用 Microsoft Visual Studio 2013 开发 Windows 8 应用程序。我需要将用户输入的数据存储在文本文件中。我编写了以下代码段来创建文件及其工作。但是文本文件是在 C:\Users 中创建的......我想在给定的文件夹中创建文本文件。如何修改我的代码以在我指定的文件夹中创建文件。

StorageFile sampleFile;
const string fileName = "Sample.txt";

【问题讨论】:

  • “Windows 8 应用程序”是指“沉浸式”/“地铁”类型的应用程序吗?这些应用程序是沙盒的,不能写入文件系统中的任意目录。我建议关注这篇文章:blog.jerrynixon.com/2012/06/…

标签: c# windows windows-phone-8 file-handling


【解决方案1】:

这是在 C 临时文件夹中创建文件的方法

String folderPath = @"C:/temp";
FileStream fs = new FileStream(folderPath + "\\Samplee.txt",FileMode.OpenOrCreate, FileAccess.Write);

【讨论】:

  • C/temp != C:/temp
  • @leppie,已更正
  • 我认为这不是正确的答案。他想将 StorageClass 类用于 Windows 应用商店应用程序。 StorageClass 适用于 Windows 8 和 Windows Phone 8 应用程序。
  • FileStream 在我的程序代码中突出显示为错误。但我正在使用 System.IO 命名空间。
【解决方案2】:

您需要设置要保存文件的目录。

试试这个

       string dirctory = @"D:\Folder Name"; //This is the location where you want to save the file

        if (!Directory.Exists(dirctory))
        {
            Directory.CreateDirectory(dirctory);
        }

        File.WriteAllText(Path.Combine(dirctory, "Sample.txt"), "Text you want to Insert");

【讨论】:

  • 我已导入 System.IO 命名空间,但目录下划线显示为错误。
【解决方案3】:

如前所述,通用应用程序是沙盒化的,这意味着您不能在任意文件夹中写入文件。

您应该查看File access sample 了解如何操作。

另外,您应该看看ApplicationData,它为您提供了很多保存用户输入数据的选择。是临时的吗,要同步吗,是设置吗?肯定有适合您需求的房产。

编辑:来自http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.applicationdata.localfolder.aspx这是你应该做的

var applicationData = Windows.Storage.ApplicationData.current;
var localFolder = applicationData.localFolder;

// Write data to a file

function writeTimestamp() {
   localFolder.createFileAsync("dataFile.txt", Windows.Storage.CreationCollisionOption.replaceExisting)
      .then(function (sampleFile) {
         var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
         var timestamp = formatter.format(new Date());

         return Windows.Storage.FileIO.writeTextAsync(sampleFile, timestamp);
      }).done(function () {      
      });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2021-03-30
    • 2016-12-14
    • 2020-03-03
    • 1970-01-01
    • 2022-06-13
    • 2018-12-02
    相关资源
    最近更新 更多