Coludn't acces the XML file in Visual Studio c# - c#

When executing the code below it shows an error at opening the file
it says the file dict.xml is already in use by some process
It shows error here
FileStream fs = new FileStream("dict.xml", FileMode.Open, FileAccess.Read);
FileStream fs = new FileStream("dict.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("dict");
for (i = 0; i <= xmlnode.Count - 1; i++)
{
w[i] = xmlnode[i].ChildNodes.Item(0).InnerText;
m[i] = xmlnode[i].ChildNodes.Item(1).InnerText;
}

If something else has a lock on the file you should still be able to read it if you specify FileShare.ReadWrite:
using (FileStream fs = new System.IO.FileStream("dict.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite) {

Related

c# FastRSyncNet - delete from destination source not working

Im trying to use FastRSyncNet library for sync between 2 folders.
It works fine when files exists in source folder and not exists in the destination folder.
when files not exists on the source folder and exists in destination folder , its not deleted.
example :
source folder -> 1.txt , 2.txt
destination folder -> 1.txt , 2.txt , 3.txt
all files transferred from source to destination.
public void sync()
{
// Create signature file
var signatureBaseFilePath = #"C:\tmp\test\r1\r1.tar.gz";
var signatureFilePath = #"C:\tmp\test\output\r1.tar.gz.octosig";
var signatureOutputDirectory = Path.GetDirectoryName(signatureFilePath);
if (!Directory.Exists(signatureOutputDirectory))
Directory.CreateDirectory(signatureOutputDirectory);
var signatureBuilder = new SignatureBuilder();
using (var basisStream = new FileStream(signatureBaseFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var signatureStream = new FileStream(signatureFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
{
signatureBuilder.Build(basisStream, new SignatureWriter(signatureStream));
}
// Create delta file
var newFilePath = #"C:\tmp\test\r2\r2.tar.gz";
var deltaFilePath = #"C:\tmp\test\output\r2.tar.gz.octodelta";
var deltaOutputDirectory = Path.GetDirectoryName(deltaFilePath);
if (!Directory.Exists(deltaOutputDirectory))
Directory.CreateDirectory(deltaOutputDirectory);
var deltaBuilder = new DeltaBuilder();
using (var newFileStream = new FileStream(newFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var signatureFileStream = new FileStream(signatureFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var deltaStream = new FileStream(deltaFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
{
deltaBuilder.BuildDelta(newFileStream, new SignatureReader(signatureFileStream, new ConsoleProgressReporter()), new AggregateCopyOperationsDecorator(new BinaryDeltaWriter(deltaStream)));
}
// Apply delta file to create new file
var newFilePath2 = #"C:\tmp\test\output\r1.tar.gz";
var newFileOutputDirectory = Path.GetDirectoryName(newFilePath2);
if (!Directory.Exists(newFileOutputDirectory))
Directory.CreateDirectory(newFileOutputDirectory);
var deltaApplier = new DeltaApplier { SkipHashCheck = false };
using (var basisStream = new FileStream(signatureBaseFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var deltaStream = new FileStream(deltaFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var newFileStream = new FileStream(newFilePath2, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
{
deltaApplier.Apply(basisStream, new BinaryDeltaReader(deltaStream, new ConsoleProgressReporter()), newFileStream);
}
}
resources : https://github.com/GrzegorzBlok/FastRsyncNet

c# Two FileStreams write to text file but just one affect file

below code:
var fs = new FileStream(#"C:\Users\Michał\Desktop\tools\test.txt",
FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
var fs2 = new FileStream(#"C:\Users\Michał\Desktop\tools\test.txt",
FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
int a = 0;
while (a < 3)
{
byte[] info = new UTF8Encoding(true).GetBytes("DEF_");
byte[] info2 = new UTF8Encoding(true).GetBytes("abc_");
fs.Write(info, 0, info.Length);
Thread.Sleep(100);
fs2.Write(info2, 0, info2.Length);
Thread.Sleep(1000);
++a;
}
fs.Close();
fs2.Close();
Why result is that in a file there is just "abc_abc_abc" ?
FileShare.ReadWrite means for me other processes/threads can write to this file in the same time in FileStream ctor call.
You can achieve the desired behavior as follows:
using (var fs = new FileStream("test.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
using (var fs2 = new FileStream("test.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
byte[] info = new UTF8Encoding(true).GetBytes("DEF_");
byte[] info2 = new UTF8Encoding(true).GetBytes("abc_");
for (int i = 0; i < 3; i++)
{
fs.Seek(0, SeekOrigin.End);
fs.Write(info, 0, info.Length);
fs.Flush();
fs2.Seek(0, SeekOrigin.End);
fs2.Write(info2, 0, info2.Length);
fs2.Flush();
}
}
Before writing, each pointer of stream must be positioned at the end. This is done using the Seek method.
After writing, you need to flush the buffer to disk. This ensures that the stream is in the correct state before starting the next write. To do this, use the Flush method.
When you create a stream in its constructor, you can specify the FileOptions.WriteThrough. According to its description, the intermediate buffer should not be used. However, it still doesn't work without the Flush method. Perhaps experts will explain the reason.

Read file that's already used by another process

I have a C# app that tries to read a log file which is being written to by another app. When I try to read the file, I get IOException
"The process cannot access the file ... because it is being used by
another process."
What I tried using so far are the following, but none of them fix the problem
var log = File.ReadAllText(logPath);
var stream = new FileStream(logPath, FileMode.Open);
using (var stream = File.Open(logPath, FileMode.Open))
{
}
try this:
FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader logFileReader = new StreamReader(logFileStream);
while (!logFileReader.EndOfStream)
{
string line = logFileReader.ReadLine();
// Your code here
}
// Clean up
logFileReader.Close();
logFileStream.Close();
edited with MethodMan's suggestions
using(FileStream logFileStream = new FileStream(#"c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using(StreamReader logFileReader = new StreamReader(logFileStream))
{
string text = logFileReader.ReadToEnd();
// Your code..
}
}
You can do nothing, if the "another app" does not use Share.Read while creating/opening the file.

Many FileStream's attached to one file

Like in title:
FileStream fs = new FileStream ("test.mkv", FileMode.Open);
FileStream fs1 = new FileStream ("test.mkv", FileMode.Open);
It throw an error: The process cannot access the file '...' because it is being used by another process.
But why, if it is opened for read only (?). If not, how to open file as read only?
You need to specify that you're opening it read only and that you're sharing it.
var fs1 = new FileStream("test.mkv", FileMode.Open, FileAccess.Read, FileShare.Read);
var fs2 = new FileStream("test.mkv", FileMode.Open, FileAccess.Read, FileShare.Read);

Xml editing problem using C#

I have posted a question previous regarding editing my xml document via c#
C# write to XML error
However im now having trouble with it again. Im using the exact code that worked then but getting problems again!
When I first click the button it seems to work however when I click it again I get the error
Data at the root level is invalid. Line 83, position 10
When you then open the XML document for some reason the characters "" get added to the start of the xml document so I get
"<?xml version="1.0" encoding="UTF-8"?>"
I dont understand why and its really driving me insane. I'm sure it was working before.
My code:
path = test.xml
using (FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
System.Xml.XmlDocument Temp = new System.Xml.XmlDocument();
Temp.Load(READER);
using (FileStream WRITER = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
Temp.Save(WRITER);
}
}
UPDATE #2:
I compiled your sample as is and it worked perfectly for me. I tested it with a file created straight from code and also with a xaml file created in Visual Studio. So it seems the file you're working with is corrupted or have an encoding problem.
As far as I know you can't do anything about corrupted file, but as for encoding you can specify it when reading by using a StreamReader object. You just pass a desired encoding and your reader stream to StreamReader's constructor. Also it has an option to detect the encoding from byte order marks.
using (TextReader txtreader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.GetEncoding(1251 /*desired codepage here*/)))
{
document.Load(txtreader);
}
or
using (TextReader txtreader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), true /*tries to detect the encoding*/))
{
document.Load(txtreader);
}
Of course, you should save the file using the same encoding or you'll have problems next time you run your loading code.
Also I'm attaching a code which creates a file if it doesn't exist or just modifies it if it already exists.
class Program
{
static readonly string path = #"C:\Users\Dmitry\Documents\test_3.xml";
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
test(path);
}
static void test(string path)
{
XmlDocument document = new XmlDocument();
if (File.Exists(path))
{
using (Stream readStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
document.Load(readStream);
}
}
else
{
document.AppendChild(document.CreateXmlDeclaration("1.0", "UTF-8", String.Empty));
document.AppendChild(document.CreateElement("Test"));
}
document.DocumentElement.AppendChild(document.CreateElement("Node"));
using (FileStream WRITER = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
document.Save(WRITER);
}
}
}
I hope it helps you.

Categories