I know, this question already been asked in many places repeatedly. But I’ve tried to google it and check this site for solution, but still come short. I’m still encountering this issue even after using all of the suggested solutions.
Basically, I have two separate programs. The function of each program is something like below.
- ProgramA – Function: Constantly update to the source file(txt)
- ProgramB* – Function: Constantly copy the source file to destination location.
With ProgramB, I want to sort of simulate doing the ctrl+c operation. Hence I am trying to archive where by I can update the file and operator can copy it as well.
Here is what I’ve tried so far. Below is sample program to test the functionality.
ProgramA
static void Main(string[] args)
{
// just prepare the data
List<string> tempList = new List<string>();
for(int i = 0; i < 50000; i++)
{
tempList.Add(string.Format("xxx_{0}", i.ToString()));
}
try
{
// just to simulate constart update
for (int j = 0; j < 20000; j++)
{
using (FileStream file = new FileStream(tmpFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(file))
{
foreach (string tmpName in tempList)
{
sw.WriteLine(tmpName);
}
sw.Close();
}
file.Close();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadKey();
}
}
ProgramB
static void Main(string[] args)
{
string source = @"C:\temp\test.txt";
string dest = @"C:\temp\dest\test.txt";
while (true)
{
try
{
File.Copy(source, dest, true);
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadKey();
}
}
}
Instead of using File.Copy, try using a FileStream and copying the bits yourself. The above code will get an error, as File.Copy does not specify what FileShare permissions it sets on the file.