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.
Related
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.
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
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.
I have a file which contains several text entries, say
one
two
three
Now, I need to delete one of the entries, say "two". I'm using StreamReader and StreamWriter classes. In order to delete, first, I read the contents of the file into a string using StreamReader class, replace the "two\r\n" in the read string with "" and then, I write this string to the file using the StreamWriter class. But, since the length of the newly written string i.e. "one\r\nthree\r\n" is less than the original string i.e. "one\r\ntwo\r\nthree\r\n", the first few characters get overwritten and the characters near the end still stay there giving rise to "one\r\nthree\r\nree\r\n". Seems like a simple problem but, it has me stuck. Any ideas?
The user variable contains the entry to be deleted.
string all = "";
using (IsolatedStorageFileStream isoStream = store.OpenFile("user_list", FileMode.Open))
{
using (StreamReader sr = new StreamReader(isoStream))
{
all = sr.ReadToEnd();
all = all.Replace(user + "\r\n", "");
}
}
using (IsolatedStorageFileStream isoStream = store.OpenFile("user_list", FileMode.Open))
{
using (StreamWriter sw = new StreamWriter(isoStream))
{
sw.Write(all);
sw.Flush();
}
}
You can fix the problem by changing FileMode.Open to FileMode.Create when you're opening the output file. That is:
using (IsolatedStorageFileStream isoStream =
store.OpenFile("user_list", FileMode.Create))
That will overwrite the previous file.
how to find is there a file is open or not and if open then then find its fullpath or directory.
You need to supply more information.
All the File handling classes are in System.IO. You will want to use File or FileInfo.
FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)
try
{
stream.ReadByte();
//file is not open
}
catch (IOException)
{
//it is open
}
Explanation: Open the file, try to read a byte, if it can't we know its either open or readonly.
And to get the full path you can use:
fullPath = System.IO.Path.GetFullPath(path);