I have a file path that might exist or might not exist.
I want to create / override the file, and i have this code:
string filePath = GetFilePath();
using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
xDoc.Save(file);
}
When i call using (FileStream file ...) and the file doesn't exist, it throws an Could not find a part of the path... error.
I am doing something wrong? shouldn't it create the file if doesn't exist?
FileStream can't create intermediate directories that don't exist. This question should help you.
FileMode.OpenOrCreate creates a file if it doesn't exist. If you also need to create the directory:
bool dirExists = System.IO.Directory.Exists(dir);
if(!dirExists)
System.IO.Directory.CreateDirectory(dir);
using(var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
}
OpenOrCreate
Specifies that the operating system should open a file if it exists;
otherwise, a new file should be created.
try this:
void OpenOrCreateFile()
{
try
{
string filePath = GetFilePath();
EnsureFolder(filePath); //if directory not exist create it
using(var fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
//your code
}
}
catch(Exception ex)
{
//handle exception
}
}
void EnsureFolder(string path)
{
string directoryName = Path.GetDirectoryName(path);
if ((directoryName.Length > 0) && (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
}
You can use StreamWriter has a boolean parameter append to overwrite the file it contents exits
http://msdn.microsoft.com/en-IN/library/36b035cb.aspx
public StreamWriter(
string path,
bool append
)
You can use the below given code
using System;
using System.IO;
using System.Text;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string fileName = "test.txt";
string textToAdd = "Example text in file";
using (StreamWriter writer = new StreamWriter(fileName, false))
{
writer.Write(textToAdd);
}
}
}
}
Related
I'm making an compressor / decompressor console program in Visual Studio 2017 and I want to get the filepath by dragging the input file to the console (.txt).
i'm getting the right path for inputStream for Compress() but outPutStream fails and cant find the filepath (FileMode.OpenOrCreate!?!), even if the path is hardcoded.
Program executes correctly if both variables are hardcoded, but i can't understand why System.IO.FileNotFoundException is thrown by getting input file from dragging the file to console and have the output file hardcoded.
....
string outPutFileName = #"C:\bla\bla\bla\bla\gergrgr.gzip";
public static void Compress(string inPath)
{
using (FileStream inputStream = new FileStream(inPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (FileStream outputStream = new FileStream(outPutFileName, FileMode.OpenOrCreate, FileAccess.Write))
{
using (GZipStream gzip = new GZipStream(outputStream, CompressionMode.Compress))
{
inputStream.CopyTo(gzip);
}
}
}
}
static void Main(string[] args)
{
string outPutFileName = #"C:\bla\bla\bla\bla\gergrgr.gzip";
//dummy var, cant find a better way to add '#' to variable set by console.readline
string filePath = #"test";
// info info info....
Console.WriteLine("Drag in txt file");
// Takes the path from dragged in file
string idk = Console.ReadLine();
// instead of of a loop to escape "/", just replace text in filePath
filePath = filePath.Replace("test", idk);
Compress(filePath);
}
I think the problem is actually that your app doesn't have permissions to write to the specified output location. Check the docs for FileMode.OpenOrCreate
If the file access is FileAccess.Write, Write permission is required.
The below works for me:
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApp1
{
internal class Program
{
private static readonly string outPutFileName = #"C:<my desktop directory>\gergrgr.gzip";
public static void Compress(string inPath)
{
using (var inputStream = new FileStream(inPath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (var outputStream = new FileStream(outPutFileName, FileMode.OpenOrCreate, FileAccess.Write))
{
using (var gzip = new GZipStream(outputStream, CompressionMode.Compress))
{
inputStream.CopyTo(gzip);
}
}
}
}
private static void Main(string[] args)
{
// info info info....
Console.WriteLine("Drag in txt file");
// Takes the path from dragged in file
var filePath = Console.ReadLine();
if (!string.IsNullOrEmpty(filePath))
{
Compress(filePath.Trim('\\', '"'));
}
}
}
}
Is there any way to create a text file using a name that comes from data entered in a form?
string path = #"E:\AppServ\**Example**.txt";
if (!File.Exists(path))
{
File.Create(path);
}
**Example** being the part taken from user inputted data.
Similar to this Console.Writeline("{0}", userData);
Here is an example of how to store files to the logged in users My Documents folder on windows.
You can modify the AppendUserFile function to support other file modes. This version will open the file for Appending if it exists, or create it if it doesn't exist.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
AppendUserFile("example.txt", tw =>
{
tw.WriteLine("I am some new text!");
});
Console.ReadKey(true);
}
private static bool AppendUserFile(string fileName, Action<TextWriter> writer)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string filePath = Path.Combine(path, fileName);
FileStream fs = null;
if (File.Exists(filePath))
fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read);
else
fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read);
using (fs)
{
try
{
TextWriter tw = (TextWriter)new StreamWriter(fs);
writer(tw);
tw.Flush();
return true;
}
catch
{
return false;
}
}
}
}
}
I wanted to save the unzipped file to a folder in IsolatedStorage. I have read the file zip file from IsolatedStorage and now want to unzip them into a folder. i have tried this way :-
private async Task UnZipFile(string fileName)
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(fileName, FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(fileStream);
var filename = unzip.FileNamesInZip.FirstOrDefault();
if (filename != null)
{
// i can have the stream too. like this.
// var zipStream = unzip.GetFileStream(filename)
// here i am not getting how to save unzip file to a folder.
}
}
Here is what i got :) Hope it will help somebody.
private async Task UnZipFile()
{
// you can use Isolated storage too
var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (var fileStream = Application.GetResourceStream(new Uri("sample.zip", UriKind.Relative)).Stream)
{
var unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip)
{
if (!string.IsNullOrEmpty(filename))
{
if (filename.Any(m => m.Equals('/')))
{
myIsolatedStorage.CreateDirectory(filename.Substring(0, filename.LastIndexOfAny(new char[] { '/' })));
}
//save file entry to storage
using (var streamWriter =
new StreamWriter(new IsolatedStorageFileStream(filename,
FileMode.Create,
FileAccess.ReadWrite,
myIsolatedStorage)))
{
streamWriter.Write(unzip.GetFileStream(filename));
}
}
}
}
}
Here is my problem, i'm trying to make minecraft classic server and i'm using text system to make allow list for each map, problem is text system makes a file for each map and we got around 15k maps in total, so if 1k of players add allow list to their maps, it would be hard to upload / move server to another host. i want to make a zip file in main folder of my software and add each text file to it and also making it readable with system, i want to know how to read a file from GZip, and how to compress files also.
Thanks
Here is my very easy working code. No temporary file
using (FileStream reader = File.OpenRead(filePath))
using (GZipStream zip = new GZipStream(reader, CompressionMode.Decompress, true))
using (StreamReader unzip = new StreamReader(zip))
while(!unzip.EndOfStream)
ReadLine(unzip.ReadLine());
If you want to avoid creating temporary files, you can use this:
using (Stream fileStream = File.OpenRead(filePath),
zippedStream = new GZipStream(fileStream, CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(zippedStream))
{
// work with reader
}
}
Details on how to use GZip to compress and decompress. After decompression, you can use the StreamReader() class to read the contents of the file (.NET 4.0).
using System;
using System.IO;
using System.IO.Compression;
namespace zip
{
public class Program
{
public static void Main()
{
string directoryPath = #"c:\users\public\reports";
DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);
foreach (FileInfo fileToCompress in directorySelected.GetFiles())
{
Compress(fileToCompress);
}
foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz"))
{
Decompress(fileToDecompress);
}
}
public static void Compress(FileInfo fileToCompress)
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), compressedFileStream.Length.ToString());
}
}
}
}
}
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
}
}
}
}
}
}
Source
I keep getting the following error when I try to write to a temporary file:
The process cannot access the file
'C:\Users\jdoe\AppData\Local\Temp\jdoe.tmp' because it is being used
by another process.
These are the only methods that do anything with the file:
private void LoadData(string filePath)
{
if (!File.Exists(filePath))
{
File.Create(filePath);
return;
}
var fileDetails = new FileInfo(filePath);
if (fileDetails.Length > 0)
{
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
// Do stuff...
fileStream.Close();
}
}
}
private void SaveData(string filePath)
{
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
// Do stuff...
fileStream.Close();
}
}
What is locking the file?
Turns out File.Create(filePath) returns a FileStream, which needs to be closed. The error disappeared by simply changing the File.Create() to this:
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
return;
}
you have to remove fist block of the code..
because when you will write .. if file is not there it will create the file or if file already there then it should append..