System.IO.IOException: Sharing violation on path in C#

大憨熊 提交于 2020-01-22 02:21:05

问题


I have used below code to save the file in xamarin forms ios but give me

System.IO.IOException: Sharing violation

please help me.

FileStream fileStream = File.Open(pdfPath, FileMode.Create);
stream.Position = 0;
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Close();

回答1:


Have you checked that your app has permission for accessing files on the system? Also i would to a check to see if the files exist before opening it with File.Exists();.

Also there are better ways of reading and writing to files in C#:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile.txt");

using (var streamWriter = new StreamWriter(filename, true))
{
    streamWriter.WriteLine(DateTime.UtcNow);
}

using (var streamReader = new StreamReader(filename))
{
    string content = streamReader.ReadToEnd();
    System.Diagnostics.Debug.WriteLine(content);
}



回答2:


You can try disposing the file stream before writing to a file.

FileStream fileStream = File.Open(pdfPath, FileMode.Create);
stream.Position = 0;
stream.CopyTo(fileStream);
fileStream.Flush();
fileStream.Close();
fileStream.Dispose();
File.WriteAllBytes(pdfPath, bArray);


来源:https://stackoverflow.com/questions/59423877/system-io-ioexception-sharing-violation-on-path-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!