-1

Here is my code: enter image description here

using System.IO;

namespace Randoms
{
    public class Program
    {
        public static void Main()
        {
            byte[] buffer = new byte[10240]; // buffer size
            string path = @"C:\Users\RAHUL\Desktop\file.txt";
            using (FileStream source = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                long fileLength = source.Length;
                using (FileStream dest = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    long totalBytes = 0;
                    int currentBlockSize = 0;

                    while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        totalBytes += currentBlockSize;
                        double percentage = (double)totalBytes * 100.0 / fileLength;
                        dest.Write(buffer, 0, currentBlockSize);                                                
                    }
                }
            }
        }
    }
}

Please check the image which shows the error which I am getting.I have tried to change the FileAccess multiple times but not getting any luck.

RahulGo8u
  • 148
  • 2
  • 19
  • 2
    You create two stream from the same file so it won't work. What are you trying to do ? Can you explain a little bit more. It seems that you open a file read it and try to write the exact same thing into the same file ??? – Thomas Jun 07 '17 at 00:40
  • Actually I am reading the file first then I need to do perform some changes in the file. Here I have shown image file but I have to use .txt, .doc, .job files. After reading the file I need to write in it and finally save/update in the same location. – RahulGo8u Jun 07 '17 at 00:52

2 Answers2

0

This post explains how to both read and write to a file using a single stream:

How to both read and write a file in C#

Consider you may have the file still open from a previous erroneous run. Use a tool like Sysinternals Process Monitor or Unlocker to verify it isn't open by another instance.

How to use Process Monitor:

http://www.manuelmeyer.net/2013/09/tooltips-unlocking-files-with-sysinternals-process-monitor/

Ryan R.
  • 2,478
  • 5
  • 27
  • 48
0

Both source and dest are referencing the same file. In the first instance (source) you open it exclusively (ie not shared).

In the second instance (dest) you now want to create the file which you opened in the first instance, but allow it to be shared.

Since the source is already open an in use you cannot write over the top of it using dest.

I think what you may be really want is to have the path parameter for the dest to be different to path parameter for the source, since you are essentially trying to re-write the same data into the same file at the same location right now.

Jens Meinecke
  • 2,904
  • 17
  • 20