Copy FIlestream to new stream giving empty file - c#

I'm working on converting some files, but I'm having some issues on the 2nd step of this.
Load file from source location
Save file to temp folder
Save converted file to Output location
I have 2 methods for reading the original file, but there is a problem with both of them.
Method 1: The file remains locked (so when something goes wrong, I have to restart the app)
Method 2: The temp file is empty
Anybody got an idea on how to fix one of those problems?
Utilities class
/// <summary>
/// Get document stream
/// </summary>
/// <param name="DocumentName">Input document name</param>
public static Stream GetDocumentStreamFromLocation(string documentLocation)
{
try
{
//ExStart:GetDocumentStream
// Method one: works, but locks file
return File.Open(documentLocation, FileMode.Open, FileAccess.Read);
// Method two: gives empty file on temp folder
using (FileStream fsSource = File.Open(documentLocation, FileMode.Open, FileAccess.Read))
{
var stream = new MemoryStream((int)fsSource.Length);
fsSource.CopyTo(stream);
return stream;
}
//ExEnd:GetDocumentStream
}
catch (FileNotFoundException ioEx)
{
Console.WriteLine(ioEx.Message);
return null;
}
}
/// <summary>
/// Save file in any format
/// </summary>
/// <param name="filename">Save as provided string</param>
/// <param name="content">Stream as content of a file</param>
public static void SaveFile(string filename, Stream content, string location = OUTPUT_PATH)
{
try
{
//ExStart:SaveAnyFile
//Create file stream
using (FileStream fileStream = File.Create(Path.Combine(Path.GetFullPath(location), filename)))
{
content.CopyTo(fileStream);
}
//ExEnd:SaveAnyFile
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I Call the following functions as following:
public static StreamContent Generate(string sourceLocation)
{
// Get filename
var fileName = Path.GetFileName(sourceLocation);
// Create tempfilename
var tempFilename = $"{Guid.NewGuid()}_{fileName}";
// Put file in storage location
Utilities.SaveFile(tempFilename, Utilities.GetDocumentStreamFromLocation(sourceLocation), Utilities.STORAGE_PATH);
// ... More code
}

In order to copy the source file to a temp folder, the easiest way is to use the File.Copy method from the System.IO namespace. Consider the following:
// Assuming the variables have been set as you already had, this creates a copy in the intended location.
File.Copy(documentLocation, filename);

After some further digging. I found out that you can add a property in the File.Open that "fixes" this issue:
return File.Open(documentLocation, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
With the downside that you still can't move / rename the file, but the lock is removed.

Related

Extract ZIP file to memory (not disk)

I need to extract a zip file to memory (not to the disk). I cannot save it to a directory, even temporarily.
Is there a way to extract a zip file just to memory, and perform "File" functions there?
I can't open the file as a file stream because this doesn't allow me to read the metadata (last write time, attributes, etc). Some but not all the file attributes can be read from zip entry itself but this is insufficient for my purposes.
I've been using:
using (ZipArchive archive = ZipFile.OpenRead(openFileDialog.FileName)) // Read files from the zip file
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if(entry.Name.EndsWith(".txt", StringComparison.InvariantCultureIgnoreCase)) // get .txt file
{
FileStream fs = entry.Open() as FileStream;
}
}
}
Thanks.
The code below presents a way to get the file into memory as an array of strings, but it is unclear as to what file functions you are asking for. Other commenters have mentioned ExternalAttributes, which is OS dependent therefore it is relevant to have more information as to the problem space.
using System;
using System.IO;
using System.IO.Compression;
namespace StackOverflowSampleCode
{
class Program
{
/// <summary>
/// Validate the extension is correct
/// </summary>
/// <param name="entry"></param>
/// <param name="ext"></param>
/// <returns></returns>
static bool validateExtension(ZipArchiveEntry entry, string ext)
{
return entry.Name.EndsWith(
ext,
StringComparison.InvariantCultureIgnoreCase);
}
/// <summary>
/// Convert the entry into an array of strings
/// </summary>
/// <param name="entry"></param>
/// <returns></returns>
static string[] extractFileStrings(ZipArchiveEntry entry)
{
string[] file;
// Store into MemoryStream
using (var ms = entry.Open() as MemoryStream)
{
// Verify we are at the start of the stream
ms.Seek(0, SeekOrigin.Begin);
// Handle the bytes of the memory stream
// by converting to array of strings
file = ms.ToString().Split(
Environment.NewLine, // OS agnostic
StringSplitOptions.RemoveEmptyEntries);
}
return file;
}
static void Main(string[] args)
{
string fileName = "";
using (ZipArchive archive = ZipFile.OpenRead(fileName))
{
foreach (var entry in archive.Entries)
{
// Limit results to files with ".txt" extension
if (validateExtension(entry, ".txt"))
{
var file = extractFileStrings(entry);
foreach (var line in file)
{
Console.WriteLine(line);
}
Console.WriteLine($"Last Write Time: {entry.LastWriteTime}");
Console.WriteLine($"External Attributes: {entry.ExternalAttributes}");
}
}
}
}
}
}

c# Detect if file has finished being written

I am writing a PowerPoint add-in that FTPs a file that has been converted to a WMV.
I have the following code which works fine:
oPres.CreateVideo(exportName);
oPres.SaveAs(String.Format(exportPath, exportName),PowerPoint.PpSaveAsFileType.ppSaveAsWMV,MsoTriState.msoCTrue);
But this kicks off a process within PP which does the file conversion and it immediately goes to the next line of code before the file has finished being written.
Is there a way to detect when this file has finished being written so I can run the next line of code knowing that the file has been finished?
When a file is being used it is unavailable, so you could check the availability and wait until the file is available for use. An example:
void AwaitFile()
{
//Your File
var file = new FileInfo("yourFile");
//While File is not accesable because of writing process
while (IsFileLocked(file)) { }
//File is available here
}
/// <summary>
/// Code by ChrisW -> http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use
/// </summary>
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}

Is there a way to delete a folder the same way we delete a file automatically?

Using FileOptions.DeleteOnClose we can have a file delete itself when the last handle has been closed, this is very useful for temporary files that you want deleted when the program is closed. I created the following function
/// <summary>
/// Create a file in the temp directory that will be automatically deleted when the program is closed
/// </summary>
/// <param name="filename">The name of the file</param>
/// <param name="file">The data to write out to the file</param>
/// <returns>A file stream that must be kept in scope or the file will be deleted.</returns>
private static FileStream CreateAutoDeleteFile(string filename, byte[] file)
{
//get the GUID for this assembly.
var attribute = (GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0];
var assemblyGuid = attribute.Value;
//Create the folder for the files to be saved in.
string folder = Path.Combine(Path.GetTempPath(), assemblyGuid);
Directory.CreateDirectory(folder);
var fs = new FileStream(Path.Combine(folder, filename), FileMode.OpenOrCreate, FileAccess.ReadWrite,
FileShare.ReadWrite, 16 << 10, //16k buffer
FileOptions.DeleteOnClose);
//Check and see if the file has already been created, if not write it out.
if (fs.Length == 0)
{
fs.Write(file, 0, file.Length);
fs.Flush();
}
return fs;
}
Everything works perfectly but I leave a leftover folder in the users %TEMP% folder. I would like to be a good citizen and also delete the folder when I am done but I don't think there is a way to do that like I do with files.
Is there a way to auto-delete the folder like I delete the file, or am I just going to have to live with the folder remaining or having to explicitly call Directory.Delete when my program closes.

File Read-only access irrespective of locks (C#)

How do I open (using c#) a file that is already open (in MS Word, for instance)? I thought if I open the file for read access e.g.
FileStream f= new FileStream('filename', FileMode.Open, FileAccess.ReadWrite);
I should succeed, but I get an exception:
"the process cannot access the file
because it is locked ..."
I know there must be a way to read the file irrespective of any locks placed on it, because I can use windows explorer to copy the file or open it using another program like Notepad, even while it is open in WORD.
However, it seems none of the File IO classes in C# allows me to do this. Why?
You want to set FileAccess=Read and FileShare=ReadWrite. Here is a great article on this (along with an explanation of why):
http://coding.infoconex.com/post/2009/04/How-do-I-open-a-file-that-is-in-use-in-C.aspx
Your code is using the FileAccess.Read*Write* flag. Try just Read.
I know this is an old post. But I needed this and I think this answer can help others.
Copying a locked file the way the explorer does it.
Try using this extension method to get a copy of the locked file.
Usage example
private static void Main(string[] args)
{
try
{
// Locked File
var lockedFile = #"C:\Users\username\Documents\test.ext";
// Lets copy this locked file and read the contents
var unlockedCopy = new
FileInfo(lockedFile).CopyLocked(#"C:\Users\username\Documents\test-copy.ext");
// Open file with default app to show we can read the info.
Process.Start(unlockedCopy);
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
}
}
Extension method
internal static class LockedFiles
{
/// <summary>
/// Makes a copy of a file that was locked for usage in an other host application.
/// </summary>
/// <returns> String with path to the file. </returns>
public static string CopyLocked(this FileInfo sourceFile, string copyTartget = null)
{
if (sourceFile is null)
throw new ArgumentNullException(nameof(sourceFile));
if (!sourceFile.Exists)
throw new InvalidOperationException($"Parameter {nameof(sourceFile)}: File should already exist!");
if (string.IsNullOrWhiteSpace(copyTartget))
copyTartget = Path.GetTempFileName();
using (var inputFile = new FileStream(sourceFile.FullName, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite))
using (var outputFile = new FileStream(copyTartget, FileMode.Create))
inputFile.CopyTo(outputFile, 0x10000);
return copyTartget;
}
}

FileStream StreamReader problem in C#

I'm testing how the classes FileStream and StreamReader work togheter. Via a Console application.
I'm trying to go in a file and read the lines and print them on the console.
I've been able to do it with a while-loop, but I want to try it with a foreach loop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace testing
{
public class Program
{
public static void Main(string[] args)
{
string file = #"C:\Temp\New Folder\New Text Document.txt";
using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using(StreamReader sr = new StreamReader(fs))
{
foreach(string line in file)
{
Console.WriteLine(line);
}
}
}
}
}
}
The error I keep getting for this is: Cannot convert type 'char' to 'string'
The while loop, which does work, looks like this:
while((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
I'm probably overlooking something really basic, but I can't see it.
If you want to read a file line-by-line via foreach (in a reusable fashion), consider the following iterator block:
public static IEnumerable<string> ReadLines(string path)
{
using (StreamReader reader = File.OpenText(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
Note that this this is lazily evaluated - there is none of the buffering that you would associate with File.ReadAllLines(). The foreach syntax will ensure that the iterator is Dispose()d correctly even for exceptions, closing the file:
foreach(string line in ReadLines(file))
{
Console.WriteLine(line);
}
(this bit is added just for interest...)
Another advantage of this type of abstraction is that it plays beautifully with LINQ - i.e. it is easy to do transformations / filters etc with this approach:
DateTime minDate = new DateTime(2000,1,1);
var query = from line in ReadLines(file)
let tokens = line.Split('\t')
let person = new
{
Forname = tokens[0],
Surname = tokens[1],
DoB = DateTime.Parse(tokens[2])
}
where person.DoB >= minDate
select person;
foreach (var person in query)
{
Console.WriteLine("{0}, {1}: born {2}",
person.Surname, person.Forname, person.DoB);
}
And again, all evaluated lazily (no buffering).
To read all lines in New Text Document.txt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace testing
{
public class Program
{
public static void Main(string[] args)
{
string file = #"C:\Temp\New Folder\New Text Document.txt";
using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using(StreamReader sr = new StreamReader(fs))
{
while(!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
}
}
}
}
I have a LineReader class in my MiscUtil project. It's slightly more general than the solutions given here, mostly in terms of the way you can construct it:
From a function returning a stream, in which case it will use UTF-8
From a function returning a stream, and an encoding
From a function which returns a text reader
From just a filename, in which case it will use UTF-8
From a filename and an encoding
The class "owns" whatever resources it uses, and closes them appropriately. However, it does this without implementing IDisposable itself. This is why it takes Func<Stream> and Func<TextReader> instead of the stream or the reader directly - it needs to be able to defer the opening until it needs it. It's the iterator itself (which is automatically disposed by a foreach loop) which closes the resource.
As Marc pointed out, this works really well in LINQ. One example I like to give is:
var errors = from file in Directory.GetFiles(logDirectory, "*.log")
from line in new LineReader(file)
select new LogEntry(line) into entry
where entry.Severity == Severity.Error
select entry;
This will stream all the errors from a whole bunch of log files, opening and closing as it goes. Combined with Push LINQ, you can do all kinds of nice stuff :)
It's not a particularly "tricky" class, but it's really handy. Here's the full source, for convenience if you don't want to download MiscUtil. The licence for the source code is here.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace MiscUtil.IO
{
/// <summary>
/// Reads a data source line by line. The source can be a file, a stream,
/// or a text reader. In any case, the source is only opened when the
/// enumerator is fetched, and is closed when the iterator is disposed.
/// </summary>
public sealed class LineReader : IEnumerable<string>
{
/// <summary>
/// Means of creating a TextReader to read from.
/// </summary>
readonly Func<TextReader> dataSource;
/// <summary>
/// Creates a LineReader from a stream source. The delegate is only
/// called when the enumerator is fetched. UTF-8 is used to decode
/// the stream into text.
/// </summary>
/// <param name="streamSource">Data source</param>
public LineReader(Func<Stream> streamSource)
: this(streamSource, Encoding.UTF8)
{
}
/// <summary>
/// Creates a LineReader from a stream source. The delegate is only
/// called when the enumerator is fetched.
/// </summary>
/// <param name="streamSource">Data source</param>
/// <param name="encoding">Encoding to use to decode the stream
/// into text</param>
public LineReader(Func<Stream> streamSource, Encoding encoding)
: this(() => new StreamReader(streamSource(), encoding))
{
}
/// <summary>
/// Creates a LineReader from a filename. The file is only opened
/// (or even checked for existence) when the enumerator is fetched.
/// UTF8 is used to decode the file into text.
/// </summary>
/// <param name="filename">File to read from</param>
public LineReader(string filename)
: this(filename, Encoding.UTF8)
{
}
/// <summary>
/// Creates a LineReader from a filename. The file is only opened
/// (or even checked for existence) when the enumerator is fetched.
/// </summary>
/// <param name="filename">File to read from</param>
/// <param name="encoding">Encoding to use to decode the file
/// into text</param>
public LineReader(string filename, Encoding encoding)
: this(() => new StreamReader(filename, encoding))
{
}
/// <summary>
/// Creates a LineReader from a TextReader source. The delegate
/// is only called when the enumerator is fetched
/// </summary>
/// <param name="dataSource">Data source</param>
public LineReader(Func<TextReader> dataSource)
{
this.dataSource = dataSource;
}
/// <summary>
/// Enumerates the data source line by line.
/// </summary>
public IEnumerator<string> GetEnumerator()
{
using (TextReader reader = dataSource())
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
/// <summary>
/// Enumerates the data source line by line.
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
The problem is in:
foreach(string line in file)
{
Console.WriteLine(line);
}
Its because the "file" is string, and string implements IEnumerable. But this enumerator returns "char" and "char" can not be implictly converted to string.
You should use the while loop, as you sayd.
Slightly more elegant is the following...
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
using (var streamReader = new StreamReader(fileStream))
{
while (!streamReader.EndOfStream)
{
yield return reader.ReadLine();
}
}
}
Looks like homework to me ;)
You're iterating over the filename (a string) itself which gives you one character at a time. Just use the while approach that correctly uses sr.ReadLine().
Instead of using a StreamReader and then trying to find lines inside the String file variable, you can simply use File.ReadAllLines:
string[] lines = File.ReadAllLines(file);
foreach(string line in lines)
Console.WriteLine(line);
You are enumerating a string, and when you do that, you take one char at the time.
Are you sure this is what you want?
foreach(string line in file)
A simplistic (not memory efficient) approach of iterating every line in a file is
foreach (string line in File.ReadAllLines(file))
{
..
}
I presume you want something like this:
using ( FileStream fileStream = new FileStream( file, FileMode.Open, FileAccess.Read ) )
{
using ( StreamReader streamReader = new StreamReader( fileStream ) )
{
string line = "";
while ( null != ( line = streamReader.ReadLine() ) )
{
Console.WriteLine( line );
}
}
}

Categories

Resources