系统.将文件读入字节数组时出现ArgumentException异常

本文关键字:ArgumentException 异常 数组 字节数 文件 字节 系统 | 更新日期: 2023-09-27 18:18:53

要使用ByteArrayContentHttpClient上传文件,我正在将StorageFile读取到byte数组中。代码工作没有问题的图像,但它不工作的文件通过AudioVideoCaptureDevice生成-即使通过文件不是空的,我仔细检查。*它将以任何方式访问文件:

byte[] data;
StorageFolder folder = ApplicationData.Current.LocalFolder;
try {
    Debug.WriteLine("uploading: "+ fileName);
    StorageFile file = await folder.GetFileAsync("data''"+LocalPayload);
    var probs = await file.GetBasicPropertiesAsync();
    Debug.WriteLine("path " + file.Path + "" + " size " + probs.Size);
    try
    {
        var stream = await file.OpenReadAsync();
        using (var dataReader = new DataReader(stream))
        {
            Debug.WriteLine("stream size is " + stream.Size);
            data = new byte[stream.Size];
            await dataReader.LoadAsync((uint)stream.Size);
            dataReader.ReadBytes(data);
        }
        Debug.WriteLine("stream was read");
        content = new ByteArrayContent(data);
    }
    catch (System.IO.FileNotFoundException e)
    {
        Debug.WriteLine("file not found", e.ToString());
        return;
    }
    catch (Exception e)
    {
        Debug.WriteLine("could not create byte array for file: " + e.ToString());
        return;
    }
}
catch (Exception e)
{
    Debug.WriteLine("could not read file: " + e.ToString());
    return;
}

这是一个例外

could not read file: System.ArgumentException: Value does not fall within the expected range.
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at TestApp.Models.Item.<Upload>d__1f.MoveNext()

要捕获文件,我首先使用录制声音

IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
var dataFolder = await applicationFolder.CreateFolderAsync("data", CreationCollisionOption.OpenIfExists);
outputFile = await dataFolder.CreateFileAsync(audioFileName, CreationCollisionOption.ReplaceExisting);
stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite);
await dev.StartRecordingToStreamAsync(stream);

在一些用户交互之后,我调用

await dev.StopRecordingAsync();
Debug.WriteLine("stopped recording");
await stream.FlushAsync();
stream.Dispose();

有什么建议为什么有些文件可以工作,有些不能?

谢谢!

UPDATE添加了创建文件和文件夹源的代码

UPDATE2增加了周围try catch读取文件大小的代码

系统.将文件读入字节数组时出现ArgumentException异常

问题是由于声音文件的文件名错误。我保存了绝对路径,而不仅仅是上面代码中使用的文件名。

感谢所有试图帮助我的人!