OneDrive中Visual Studio项目存文件遇DirectoryNotFoundException求助
问题:OneDrive路径下控制台应用文件操作报错
我正在开发一个小型控制台应用程序重新熟悉编程,功能是将文件转换为字节数组后保存到项目内的另一个文件夹,逻辑十分简单,但尝试访问测试文件或保存转换后的文件时出现错误。
本地C盘测试相同功能正常,但将项目放在OneDrive中时,遇到如下错误:
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\gavin\OneDrive\Documents\Portfolio\ByteConverter\bin\Debug\net6.0\ConvertedToByte\test'.'
希望将项目保留在OneDrive中,这是否可行?或是需要开启Visual Studio中某个未知功能?
补充代码
using System.IO; namespace BystConverter { public class converter { static void Main(string[] args) { Console.WriteLine("Hello, World!"); // 错误异常发生在此处 File.WriteAllBytes("ConvertedToByte/test",SaveByteArrayToFile("C:/Users/gavin/Documents/Testfiles/925821-DDAL_08-02_Beneath_the_City_of_the_Dead_V1.0.pdf")); Console.WriteLine("Complete"); } public static byte[] SaveByteArrayToFile(string filepath) { byte[] filebyteArray = File.ReadAllBytes(filepath); return filebyteArray; } } }
解决方案
- 问题本质:
File.WriteAllBytes不会自动创建不存在的目录,OneDrive路径下的ConvertedToByte文件夹未提前创建,因此报错。本地C盘测试正常大概率是你手动创建过该文件夹,而OneDrive项目目录下没有。 - 修复步骤:
- 在写入文件前,先检查并创建目标目录:
string targetDirectory = "ConvertedToByte"; if (!Directory.Exists(targetDirectory)) { Directory.CreateDirectory(targetDirectory); } - 目标文件名建议添加扩展名(比如
test.pdf),避免无后缀文件引发的识别问题,同时用Path.Combine拼接路径更安全:string targetFilePath = Path.Combine(targetDirectory, "test.pdf"); File.WriteAllBytes(targetFilePath, SaveByteArrayToFile("C:/Users/gavin/Documents/Testfiles/925821-DDAL_08-02_Beneath_the_City_of_the_Dead_V1.0.pdf"));
- 在写入文件前,先检查并创建目标目录:
- OneDrive可行性说明:完全可以将项目放在OneDrive中,无需开启Visual Studio特殊功能。只需注意OneDrive的同步状态,确保项目文件同步完成后再运行程序,避免同步延迟或文件锁定导致的异常。
内容的提问来源于stack exchange,提问作者GavWasTaken
相关产品推荐
相关产品推荐

