Well, it's just a normal filestream with streamwriter/reader, you can modify it if you wish to.
However, it will always make sure you can read/write to the chosen file and it will not throw and exception, if the file is already open in a stream, because if it is, then it will close it.
Code:
public class SafeCollector
{
public static List<SafeFileStream> Streams = new List<SafeFileStream>();
}
public class SafeFileStream
{
private System.IO.FileStream fstream;
private string m_filename;
public SafeFileStream(string FileName, bool writeall)
{
int count = 0;
m_filename = FileName;
again:
if (count <= 1)
{
count++;
try
{
if (!writeall)
fstream = new System.IO.FileStream(FileName, System.IO.FileMode.Open);
else
fstream = new System.IO.FileStream(FileName, System.IO.FileMode.Truncate);
}
catch
{
try
{
fstream = new System.IO.FileStream(FileName, System.IO.FileMode.CreateNew);
}
catch
{
foreach (SafeFileStream stream in SafeCollector.Streams)
{
if (stream.m_filename == FileName)
{
stream.Close();
goto again;
}
}
}
}
}
if (!SafeCollector.Streams.Contains(this))
SafeCollector.Streams.Add(this);
}
public void Write(string content)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fstream))
{
sw.WriteLine(content);
sw.Close();
}
}
public string Read()
{
string ret = "";
using (System.IO.StreamReader sr = new System.IO.StreamReader(fstream))
{
ret = sr.ReadToEnd();
sr.Close();
}
return ret;
}
public void Close()
{
fstream.Close();
if (SafeCollector.Streams.Contains(this))
SafeCollector.Streams.Remove(this);
}
~SafeFileStream()
{
if (SafeCollector.Streams.Contains(this))
SafeCollector.Streams.Remove(this);
}
}
Code:
SafeFileStream fs = new SafeFileStream("test.txt", true);
fs.Write("OMFG\nTROLOLOL");
fs.Close();
SafeFileStream fss = new SafeFileStream("test.txt", false);
string s = fss.Read();
fss.Close();
Code:
SafeFileStream fs = new SafeFileStream("test.txt", true);
fs.Write("OMFG\nTROLOLOL");
SafeFileStream fss = new SafeFileStream("test.txt", false);
string s = fss.Read();
fss.Close();






