Sharing violation IOException while reading and writing to file C#
Well, you're trying to open the file file_no.txt
for reading and for writing using separate streams. This may not work as the file will be locked by the reading stream, so the writing stream can't be created and you get the exception.
One solution would be to read the file first, close the stream and then write the file after increasing the fileNo
. That way the file is only opened once at a time.
Another way would be to create a file stream for both read and write access like that:
FileStream fileStream = new FileStream(@"file_no.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None);
The accepted answer to this question seems to have a good solution also, even though I assume you do not want to allow shared reads.
Possible alternate solution
I understand you want to create unique log files when your program starts. Another way to do so would be this:
int logFileNo = 1;
string fileName = String.Format("log_{0}.txt", logFileNo);
while (File.Exists(fileName))
{
logFileNo++;
fileName = String.Format("log_{0}.txt", logFileNo);
}
This increases the number until it finds a file number where the log file doesn't exist. Drawback: If you have log_1.txt
and log_5.txt
, the next file won't be log_6.txt
but log_2.txt
.
To overcome this, you could enumerate all the files in your directory with mask log_*.txt
and find the greatest number by performing some string manipulation.
The possibilities are endless :-D
System.IO.IOException: Sharing violation on path
Figured it out after finding this thread: Sharing violation IOException while reading and writing to file C#
The solution was to close the Streamwriter before reading the file using savefile.Close()
When reading text file, I have an error about sharing violation in Unity3D
You most likely are trying to read the text file while it is being written to from your other program. This is not possible, you need to wait until one program is done writing, closes the file and then Unity can open and read it.
Also, writing and reading a file in Update is a bad idea. Those are far too many disk operations, which will be incredibly slow and also makes synchronization impossible, as you already experienced.
For a solution: What's the purpose of those two programs communicating? And why so fast? If you only have updates every once in a while you could use the FileSystemWatcher class to monitor the text file and every time it changes, the changed event of the watcher will be called. But there are probably many other better solutions to your problem. Maybe SQL databases, or making it a plugin for Unity, socket communication, whatever the use case is, it depends.
System.IO.IOException: Sharing violation on path in C#
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);
}
When writing a txt file in unity, it says sharing violation on path
According to this Unity Answer post,
It looks like you still have a lock on the file you're trying to write to. And I think it might have something to do with the File.Create() method you're calling right before trying to access it with the StreamWriter.
Which matches this bit of your code and the error location:
using (File.CreateText(pathToLoad))
{
using (TextWriter writer = new StreamWriter(pathToLoad, false))
{
So you probably need to follow the same advice and call Dispose()
before passing it to the streamwriter:
File.Create("filepath").Dispose();
Side note: using
on that line is probably also not appropriate. You aren't actually declaring a variable to use, you're calling a method that returns an object that you're then forgetting about. Would probably be better to do this:
File.CreateText(pathToLoad)).Dispose();
using (TextWriter writer = new StreamWriter(pathToLoad, false))
{
writer.WriteLine("00:00:00,00/00/0000,1,1,500,20000,1500,50,20,10,5,2,1,1,0,10,50,50");
writer.Close();
}
Sharing violation on path for my logmanager
Try adding to enclose the StreamWriter
which appends the data in a lock
statement.
First, add an object to refer to:
static object _locker = new object();
Then, modify the writeExeption
method by locking the last using
statement:
lock (_locker)
{
using (StreamWriter w = File.AppendText(filepath))
{
Log(message, w);
}
}
If this still doesn't work, it means that some other application is using your file. If it works, it means that you are logging on multiple threads.
SerializationException and IOException: Sharing violation on path
I made some working code for you to try, I tried to make it as easy to edit as i could, so you can make it work for your use case.
Edit:
You need to create the folder SaveData in Assets else it doesn't work, but it will tell you that in the debug log too.
public void SavePlayerData()
{
// Create the folder path.
string t_Path = "Assets/SaveData";
// Specify the file name.
string t_FileName = "save.txt";
if( AssetDatabase.IsValidFolder( t_Path ) )
{
Debug.Log( "Found: " + t_Path );
// Create the file path.
t_FileName = t_Path + "/" + t_FileName;
if ( AssetDatabase.FindAssets( "save.txt" ).Length > 0)
{
// Create the actual text file.
TextAsset t_NewFile = new TextAsset( "" );
AssetDatabase.CreateAsset( t_NewFile, t_FileName );
}
// Add text to the created file:
string t_CopyRight = "" +
"////////////////////////////////////// \n" +
"// This save file is created // \n" +
"// by // \n" + // Copyright text.
"// Livo // \n" +
"////////////////////////////////////// \n" +
" \n";
string t_Text = "This is the frist text value"; // Random PlayerSaveData text.
string t_DiffrentText = "This is the second text value"; // Random Level text.
string t_Location = "x=100,y=0,z=250"; // Random Transform.position text.
// You can add your playerdata to these strings.
t_FileName = t_FileName.Replace( "Assets", "" );
File.WriteAllText( Application.dataPath + t_FileName, t_CopyRight + "\n" +
"[PlayerSaveData]\n" + t_Text + "\n\n" +
"[Level]\n" + t_DiffrentText + "\n\n" +
"[Location]\n" + t_Location );
AssetDatabase.SaveAssets( );
AssetDatabase.Refresh( );
}
else
{
Debug.Log( "There is no folder with that name: " + t_Path );
}
}
This is how you can import your save data:
public void LoadPlayerData()
{
string t_Path = "Assets/SaveData/save.txt";
//Read the text from directly from the test.txt file
StreamReader t_Reader = new StreamReader( t_Path );
Debug.Log( t_Reader.ReadToEnd( ) );
t_Reader.Close( );
}
BTW: The code overrides the save data each run, but i'd say that is what you want with a save file. If you want different save files, just dynamically give a new name to the t_FileName
Unity IOException: Sharing violation on path for output_log.txt, how to read a file in use?
During my local tests, I was able to access and read output_log with the following code. By the way please keep in mind that when you use File.ReadAllBytes
, it will try to access the file with the following parameters:
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,.....)
FileMode.Open → Operating system should open an existing file.
FileAccess.Read → Data can be read from the file
FileShare.Read → Allows subsequent opening of the file for reading or writing.
So basically FileAccess specifies what USER wants to do with the file. FileShare specifies what OTHERS can do with the file while the said file is being used.
Example code to read output log:
private byte[] GetBytesFromFilePath(string pathToOutputLog) {
using (var fileStream = File.Open(pathToOutputLog, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
using (var memoryStream = new MemoryStream()) {
fileStream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
Related Topics
Loading Image from Code Using Relative Path in Windows Forms
C# Quickest Way to Shift Array
How to Read and Write Id3 Tags to an Mp3 in C#
Why Doesn't Mutex Get Released When Disposed
How to Do Logging in C# Without Using 3Rd Party Libraries
How Can One Generate and Save a File Client Side Using Blazor
How to Connect to a Usb Webcam in .Net
Strings Sent Through Web API's Gets Wrapped in Quotes
How to Get Date and Time Formats Based on Culture Info
Format a Number with Commas and Decimals in C# (ASP.NET MVC3)
How to Create a Directory on Ftp Server Using C#
Wix Service Installer Overrides Service Installer Settings
Serializing/Deserializing with Memory Stream
Linq Aggregate and Group by Periods of Time
Login to the Page with Httpwebrequest
Determine Label Size Based Upon Amount of Text and Font Size in Winforms/C#