How to read and write the file using c# - c#

I want to read the file from the local system and i want to write the file again. I am writing code like:
byte[] destination = new byte[file.ContentLength];
FileInfo fil = new FileInfo(#"d:\\Projects\\file");
if (!fil.Exists)
{
using (Stream sw = fil.OpenWrite())
{
sw.Write(destination, 0, file.ContentLength);
sw.Close();
}
}
I am able to download the file but i am not able to read the file that is downloaded. Any help is appreciated

comppath + file.FileName
First, try to avoid creating file path like this. Use System.IO.Path.Combine(comppath,file.FileName) instead.
Now debug your app and check where the downloaded file is saved. Check your save and read path are same or not. If you can write file somewhere then you can also read from the same location unless some weird rules are not applied which provide write only access to you.

Related

Create file in C# from source code

I'm looking for a way to create a file from a source code (when you open a file in for example notepad it gives you some code, with that code I want to recreate the file, by stating the filetype and filename and then the code that should be in the file.
I hope you can understand my problem, it's a bit hard to explain, I'll go again...
I've got the sourcecode + filename + filetype + file description for the file that I want to create. >
Now I want C# to create a file based on that information and make it an exact copy of what that information is taken from. It should save the file, and then the file is to be openable.
Thank you in advance,
Mike
Write "code" into a file mycode.cs
string code = "code";
string filename = "mycode";
string filetype = "cs";
using (FileStream fs = File.Create(filename+"."+filetype))
{
Byte[] info = new UTF8Encoding(true).GetBytes(code);
fs.Write(info, 0, info.Length);
}
Can you just use the File.Copy method?
file.Copy("c:\temp\source.txt", "c:\temp\dest.txt");

StreamWriter doesn't write to a file that doesn't exist

I am making a level editor for my game, and most of it is working except...
When I try to save my file (XML) the file doesn't get created, and in the output box I get:
A first chance exception of type 'System.NullReferenceException'
The funny thing is that it only happens if the file doesn't exist, but it works correctly if I overwrite another file.
here is the code I'm using:
using (StreamWriter stream = new StreamWriter(filePath))
{
stream.Write(data);
stream.Close();
}
data is a string (this is not the problem because it works when I overwrite the file)
You're missing a constructor which takes a boolean that can aid in creating the file:
using (StreamWriter stream = new StreamWriter(filePath, false)) {
stream.Write(data);
stream.Close();
}
The logic is actually is little more complex than that, however:
public StreamWriter(
string path,
bool append
)
Determines whether data is to be appended to the file. If the file
exists and append is false, the file is overwritten. If the file
exists and append is true, the data is appended to the file.
Otherwise, a new file is created.
Why don't you just go around it the easy way, and check for file existence prior to writing to it:
public void Foo(string path, string data)
{
if (!File.Exists(path))
File.Create(path);
using (var sw = new StreamWriter(path, false))
{
// Work your magic.
sw.Write();
}
}
I'd really not make it any more complicated than that personally. Also, don't close the StreamWriter, the using statement disposes of it after it's served its purpose.
In my case I was running the program as non-admin, the file was to be written inside a folder that was created with administrator rights (even inside ProgramFiles or any non-admin location). The file is never created and you have to manually enable the Managed Debugging Assistants exception breaks in order to see any error.
Solution was to delete the folder and create it again with my non-admin account. Also note that StreamWriter does not create directory trees, only files.
Have you tried not using File.Create()? like so:
using (StreamWriter stream = new StreamWriter(filePath)) {
stream.Write(data);
stream.Close();
}

C# Access text file in zip archive

How can I read content of a text file inside a zip archive?
For example I have an archive qwe.zip, and insite it there's a file asd.txt, so how can I read contents of that file?
Is it possible to do without extracting the whole archive? Because it need to be done quick, when user clicks a item in a list, to show description of the archive (it needed for plugin system for another program). So extracting a whole archive isn't the best solution... because it might be few Mb, which will take at least few seconds or even more to extract... while only that single file need to be read.
You could use a library such as SharpZipLib or DotNetZip to unzip the file and fetch the contents of individual files contained inside. This operation could be performed in-memory and you don't need to store the files into a temporary folder.
Unzip to a temp-folder take the file and delete the temp-data
public static void Decompress(string outputDirectory, string zipFile)
{
try
{
if (!File.Exists(zipFile))
throw new FileNotFoundException("Zip file not found.", zipFile);
Package zipPackage = ZipPackage.Open(zipFile, FileMode.Open, FileAccess.Read);
foreach (PackagePart part in zipPackage.GetParts())
{
string targetFile = outputDirectory + "\\" + part.Uri.ToString().TrimStart('/');
using (Stream streamSource = part.GetStream(FileMode.Open, FileAccess.Read))
{
using (Stream streamDestination = File.OpenWrite(targetFile))
{
Byte[] arrBuffer = new byte[10000];
int iRead = streamSource.Read(arrBuffer, 0, arrBuffer.Length);
while (iRead > 0)
{
streamDestination.Write(arrBuffer, 0, iRead);
iRead = streamSource.Read(arrBuffer, 0, arrBuffer.Length);
}
}
}
}
}
catch (Exception)
{
throw;
}
}
Although late in the game and the question is already answered, in hope that this still might be useful for others who find this thread, I would like to add another solution.
Just today I encountered a similar problem when I wanted to check the contents of a ZIP file with C#. Other than NewProger I cannot use a third party library and need to stay within the out-of-the-box .NET classes.
You can use the System.IO.Packaging namespace and use the ZipPackage class. If it is not already included in the assembly, you need to add a reference to WindowsBase.dll.
It seems, however, that this class does not always work with every Zip file. Calling GetParts() may return an empty list although in the QuickWatch window you can find a property called _zipArchive that contains the correct contents.
If this is the case for you, you can use Reflection to get the contents of it.
On geissingert.com you can find a blog article ("Getting a list of files from a ZipPackage") that gives a coding example for this.
SharpZipLib or DotNetZip may still need to get/read the whole .zip file to unzip a file. Actually, there is still method could make you just extract special file from the .zip file without reading the entire .zip file but just reading small segment.
I needed to have insights into Excel files, I did it like so:
using (var zip = ZipFile.Open("ExcelWorkbookWithMacros.xlsm", ZipArchiveMode.Update))
{
var entry = zip.GetEntry("xl/_rels/workbook.xml.rels");
if (entry != null)
{
var tempFile = Path.GetTempFileName();
entry.ExtractToFile(tempFile, true);
var content = File.ReadAllText(tempFile);
[...]
}
}

SharpZipLib: Decompress .gz from inside .tar file?

I have a .tar file containing multiple compressed .gz files. I have no issue itterating through the .tar file creating each .gz file in a destination directory. I'd like to skip writting the .gz all together and just decompress it from the TarEntry/TarArchive? and write its contents on the fly via the .Net native GZipStream. Not even sure this is possible.
Here is my current code that writes each g'zipped file out. Not sure what to modify to get where I need to be.
using (FileStream _fsIn = new FileStream(#"F:\data\abc.tar", FileMode.Open, FileAccess.Read))
{
using (TarInputStream _tarIn = new TarInputStream(_fsIn))
{
TarEntry _tarEntry;
while ((_tarEntry = _tarIn.GetNextEntry()) != null)
{
string _archiveName = _tarEntry.Name;
using (FileStream _outStr = new FileStream(#"F:\data\" + _archiveName, FileMode.Create))
{
_tarIn.CopyEntryContents(_outStr);
}
}
}
}
I'am not sure what you want to do. Maybe you can clarify your aim. The sharpzlib is not that good documented as I Expected to be.
I've iterated through a tar archive and pushed the content of a file into a new Stream, maybe you can use this as a starting point. Have a look at this StackOverflow Article

DirectoryNotFound Exception in C#

I'm trying to save a file at path WindowsFormsApplication1\WindowsFormsApplication1\SaveFile but the following code returning me a "DirectoryNotFound" Exception with the message :
Could not find a part of the path
'D:\WindowsFormsApplication1\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\SaveFile\Hello.tx
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}
Could anyone please tell me how should I save a file at my desirable folder with specifying complete path?
When you are running in the debugger, your default path is under bin\Debug. That's what "." means in your path.
Which folder do you want to save to? You'll need to specify the full path. Perhaps you'll want to pull the path from a config file. That way, the path will be able to change based on where your application is deployed.
As the error message tells you the file will be saved in the subdirectory SaveFile under bin/debug. Before you can save a file you have to create a directory with Directory.CreateDirectory("SaveFile"). It will not be automatically created.
You need to make sure the directory exists prior to creating the text file.
String Path = #".\SaveFile\Hello.txt";
FileInfo info = new FileInfo(Path);
if (!info.Exists)
{
if (!info.Directory.Exists)
info.Directory.Create();
using (StreamWriter writer = info.CreateText())
{
writer.WriteLine("HELLO");
}
}

Categories