繁体   English   中英

System.Runtime.InteropServices.COMException发生在mscorlib.ni.dll中,但未在用户代码中处理

[英]System.Runtime.InteropServices.COMException occurred in mscorlib.ni.dll but was not handled in user code

我正在8.1中开发Windows应用程序,但出现以下错误。 我的应用程序包括将文件从本地存储移动到SD卡的过程。

我的代码如下

namespace MoveFile
{

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;
    }


    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
    }

    private async void btnCreateFolder_Click(object sender, RoutedEventArgs e)
    {

      await ReadFile();

      //Error is showing here

      **await WriteToFile();
    }
    public async Task WriteToFile()
    {
        // Get the text data from the textbox.


      byte[] fileBytes =    System.Text.Encoding.UTF8.GetBytes(this.txtSafakCount.Text.ToCharArray());

           //I got the error in this line.....showing interopservice exception

** StorageFolder knownFolder = await KnownFolders.RemovableDevices.CreateFolderAsync("bdfbdfb", CreationCollisionOption.ReplaceExisting);

        StorageFolder sdCard = (await knownFolder.GetFoldersAsync()).FirstOrDefault();

        // Create a new file named DataFile.txt.
        var file = await sdCard.CreateFileAsync("kaaaaammmmfewfwmHoJa.txt", CreationCollisionOption.ReplaceExisting);

        // Write the data from the textbox.
        using (var s = await file.OpenStreamForWriteAsync())
        {
            s.Write(fileBytes, 0, fileBytes.Length);
        }
    }
    public async Task ReadFile()
    {
        // Get the local folder.
        StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;

        if (local != null)
        {
            // Get the DataFolder folder.
            var dataFolder = await local.GetFolderAsync("DataFolder");

            // Get the file.
           await dataFolder.CreateFileAsync("DataFile.txt", CreationCollisionOption.ReplaceExisting);
            var file = await dataFolder.OpenStreamForReadAsync("DataFile.txt");

            // Read the data.
            using (StreamReader streamReader = new StreamReader(file))
            {
                this.txtSafakCount.Text = streamReader.ReadToEnd();
            }

        }
    }

}
}

我想知道为什么发生此异常以及如何解决。 提前致谢。

您做错了-首先应该获取SD卡 ,然后创建文件夹。 名为KnownFolders.RemovableDevices的名称是设备 (不是单个设备)-因此您将第一个设备称为SD卡(请注意,Universal Apps不仅适用于手机)。 因此,工作代码如下所示:

// first get the SD card
StorageFolder sdCard = (await KnownFolders.RemovableDevices.GetFoldersAsync()).FirstOrDefault();
// then perform some actions - create folders, files ...
StorageFolder myFolder = await sdCard.CreateFolderAsync("bdfbdfb", CreationCollisionOption.ReplaceExisting);

还要注意,如果要使用文件,还需要在package.appxmanifest文件中添加功能 ,并声明File Type Associations )。

您还将在MSDN上找到更多帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM