FileStream says it cant find a part of the path - c#

So i have this console app that looks through a folder for files, this folder only has .tiff images and the whole point of the app is convert them all into pdf files and finally merge them, and so I have this foreach cycle
foreach (var path in Directory.GetFiles(#"C:/Users/tferreira/Desktop/TIF_MarcadAgua"))
{
Console.WriteLine(path); // full path
Console.WriteLine(System.IO.Path.GetFileName(path)); // file name
Escrever("A fazer pdf");
imagens.Add(path.ToUpper().Replace("A.TIF", "A.PDF").Replace("A.tif", "A.PDF"));
FazerPdf(path);
if (File.Exists(path.ToUpper().Replace("A.TIF", "B.TIF")))
{
imagens.Add(path.ToUpper().Replace("A.TIF", "B.PDF"));
FazerPdf(path.ToUpper().Replace("A.TIF", "B.TIF"));
}
Escrever("O pdf foi gerado com sucesso. Caminho : " + path.ToUpper().Replace("A.TIF", "A.PDF").Replace("A.tif", "A.PDF"));
Escrever("Vai fazer o merge de todos os pdfs gerados.");
PdfMerge pm = new PdfMerge();
foreach (string imagem in imagens)
{
pm.AddDocument(imagem);
npages++;
}
}
And what is does is run trough the folder getting all the files and storing the path in that var path variable.
But when it´s actually time to make the pdf it gives that error i mentioned up top.
The line the error happens is this the fazerPDF funtion, thats where the pdf is made, since its a filepath error i will only show the error line since it keeps things easy to see.
using (FileStream stream = new FileStream(Path.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
{
// some code
}
Things i know, the images do exist, the folder does exist.
Thanks for the help, if i myself find out what it is ill post a answer.
EDIT:
fazerPDF function
static public void FazerPdf(string Path)
{
string newPath = System.IO.Path.ChangeExtension(Path, ".pdf");
if (!File.Exists(Path.Replace("TIF", "PDF")))
using (FileStream stream = new FileStream(newPath.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
{

The problem seems to be this line:
using (FileStream stream = new FileStream(Path.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
This will replace all instances of "TIF" in Path with "PDF", no matter where they appear. For example:
c:\TIFs\IlikeTIFfiles\MyTIF.TIF
Would become:
c:\PDFs\IlikePDFfiles\MyPDF.PDF
If you simply want to replace the file extension part of the path, you can use Path.ChangeExtension to cut off the old extension and add the new one:
string newPath = System.IO.Path.ChangeExtension(path, ".pdf");
using (FileStream stream = new FileStream(newPath, FileMode.Create, FileAccess.Write))
Taking the example above, #"c:\TIFs\IlikeTIFfiles\MyTIF.TIF" would become #"c:\TIFs\IlikeTIFfiles\MyTIF.pdf"
See it in action.

Related

I'm getting "The process cannot access the file because it is being used by another process" error. Any ideas?

So, I created a file and a txt file into the AppData, and I want to overwrite the txt. But when I try to do it, it keeps giving me that error. Any ideas?
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string setuppath = (path + "\\");
string nsetuppath = (setuppath + "newx" + "\\");
Directory.CreateDirectory(nsetuppath);
string hedef2 = (nsetuppath + "commands.txt");
File.Create(hedef2);
StreamWriter sw = new StreamWriter(hedef2); ----> This is where the error appears.
sw.WriteLine("Testtest");
Just use the using statement when using streams. The using statement automatically calls Dispose on the object when the code that is using it has completed.
//path to the file you want to create
string path = #"C:\code\Test.txt";
// Create the file, or overwrite if the file exists.
using (FileStream fs = File.Create(path))
{
byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
There are many ways of manipulate streams, keep it simple depending on your needs

Extract files from stream containing zip

I am making a GET request using HttpClient to download a zip file from the internet.
I want to extract all the files contained in the zip file without saving the zip file to disk.
Currently, I am able to download and save the zip file to disk, extract its contents and then delete the zip file from disk. This perfectly fine. However, I want to optimize the process.
I found a way to extract the contents directly from the downloaded zip stream but I have to specify the filenames and extensions.
I am not sure how to extract the contents while preserving their original filenames and extensions without me specifying them.
Current Approach:
string requestUri = "https://www.nuget.org/api/v2/package/" + PackageName + "/" + PackageVersion;
HttpResponseMessage response = await client.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
using Stream PackageStream = await response.Content.ReadAsStreamAsync();
SaveStream($"{DownloadPath}.zip", PackageStream);
ZipFile.ExtractToDirectory($"{DownloadPath}.zip", ExtractPath);
File.Delete($"{DownloadPath}.zip");
// Directly extract Zip contents without saving file and without losing filename and extension
using (ZipArchive archive = new ZipArchive(await response.Content.ReadAsStreamAsync()))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
using (Stream stream = entry.Open())
{
using (FileStream file = new FileStream("file.txt", FileMode.Create, FileAccess.Write))
{
stream.CopyTo(file);
}
}
}
}
.NET 4.8
.NET Core 3.1
C# 8.0
Any help in this regards would be appreciated.
Please feel free to comment on alternative approaches or suggestions.
Thank you in advance.
ZipArchiveEntry has a Name and FullName property that can be used to get the names of the files within the archive while preserving their original filenames and extensions
The FullName property contains the relative path, including the subdirectory hierarchy, of an entry in a zip archive. (In contrast, the Name property contains only the name of the entry and does not include the subdirectory hierarchy.)
For example
using (ZipArchive archive = new ZipArchive(await response.Content.ReadAsStreamAsync())) {
foreach (ZipArchiveEntry entry in archive.Entries) {
using (Stream stream = entry.Open()) {
string destination = Path.GetFullPath(Path.Combine(downloadPath, entry.FullName));
var directory = Path.GetDirectoryName(destination);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
using (FileStream file = new FileStream(destination, FileMode.Create, FileAccess.Write)) {
await stream.CopyToAsync(file);
}
}
}
}
will extract the files in the same subdirectory hierarchy as they were stored in the archive while if entry.Name was used, all the files would be extracted to the same location.

USING FileStream and handling its weird exceptions

The following code works for me when i have a fixed file+filepath declared in my code and is understood to work.
NetworkStream netStream = client.GetStream();
string FileName = #"D:\John\FYL\video1.mp4";
Directory.CreateDirectory(Path.GetDirectoryName(FileName));
using (FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
netStream.Close();
}
But fails for this protion.
NetworkStream netStream = client.GetStream();
// FileName is taken at run time on button click from textbox.
using (FileStream fs = new FileStream(#"D:\John\FYL\"+FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
netStream.Close();
}
Now when i checked another case, using File.Create and getting FileName at run-time it works.
FileStream output = File.Create(#"D:\John\" + FileName)
I'm in doubt because i have to get the saving location at run-time from Browse dialog but why FileStream fs = new FileStream(#"D:\John\FYL\+FileName throws exceptions like System.IO.DirectoryNotFoundException and System.UnauthorizedAcessException although i changed security settings for my local drives.
Does thread affecting all this as this code is a part of code loaded at run-time and browse is a click event ?
You need to ensure that the directory exists before trying to create the file.
NetworkStream netStream = client.GetStream();
if (!Directory.Exists(#"D:\John\FYL\" + FileName)) {
Directory.CreateDirectory(#"D:\John\FYL\" + FileName);
}
using (FileStream fs = new
FileStream(#"D:\John\FYL\" + FileName, FileMode.OpenOrCreate, FileAccess.Write))
{
netStream.CopyTo(fs);
}
netStream.Close();
You may also want to check that the variable FileName is properly formatted. Since you are already providing a trailing backslash "D:\John\FYL\", check that FileName is not \File1.mp4, which will concatenate into "D:\John\FYL\\File1.mp4", which is incorrect.
have you tried looking at the value of FileName? probably it's giving wrong value.
If File name contains only the name of the file, then be sure to give the name along with file extension, if there isn't any extension provided, your program will treat the name as a directory extension which it is not able to find.
If the File name contains the name along with directory heirarchy then you are simply concatenating one directory to your "D:\John\" directory which again is wrong.

How I can display Stream on the page?

I have a WCF method that I am calling, the method suppose to create a file but it create an exception. I try to find what is in the stream request that I am passing to this method. How I can alert or write this stream so I can find the content. That is my method:
Stream UploadImage(Stream request)
{
Stream requestTest = request;
HttpMultipartParser parser = new HttpMultipartParser(request, "data");
string filePath = "";
string passed = "";
if (parser.Success)
{
// Save the file somewhere
//File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
// Save the file
//SaveFile( mtp.Filename, mtp.ContentType, mtp.FileContents);
FileStream fileStream = null;
BinaryWriter writer = null;
try
{
filePath = HttpContext.Current.Server.MapPath("Uploded\\test.jpg"); // BuildFilePath(strFileName, true);
filePath = filePath.Replace("SSGTrnService\\", "");
fileStream = new FileStream(filePath, FileMode.Create);
it produces an error on this line :
fileStream = new FileStream(filePath, FileMode.Create);
that I try to understand why file can not created.
Given the information you gave, I can only assume that your code tries to create the file test.jpg somewhere where your application is not allowed to write. A common mistake would be somewhere in the Program files folder. In modern Windows versions, that is specially protected.

How to get a file and move it out of the isolated storage?

I want to take a file that stored already in the isolated storage, and copy it out, somewhere on the disk.
IsolatedStorageFile.CopyFile("storedFile.txt","c:\temp")
That doesn't work. Throws IsolatedStorageException and says "Operation not permitted"
I don't see anything in the docs, other than this, which just says that "Some operations aren't permitted", but doesn't say what, exactly. My guess is that it doesn't want you copying out of isolated storage to arbitrary locations on disk. The docs do state that the destination can't be a directory, but even if you fix that, you still get the same error.
As a workaround, you can open the file, read its contents, and write them to another file like so.
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
{
//write sample file
using (Stream fs = new IsolatedStorageFileStream("test.txt", FileMode.Create, store))
{
StreamWriter w = new StreamWriter(fs);
w.WriteLine("test");
w.Flush();
}
//the following line will crash...
//store.CopyFile("test.txt", #"c:\test2.txt");
//open the file backup, read its contents, write them back out to
//your new file.
using (IsolatedStorageFileStream ifs = store.OpenFile("test.txt", FileMode.Open))
{
StreamReader reader = new StreamReader(ifs);
string contents = reader.ReadToEnd();
using (StreamWriter sw = new StreamWriter("nonisostorage.txt"))
{
sw.Write(contents);
}
}
}

Categories

Resources