i am actually working on an application where a blob file is retrieved from my database, converted to the original file and then saved on the desktop. I would like to know if it is possible to check if a file named "xxx" already exists on the desktop and then it shall prompt me for another name. Here is my code:
myData.Read();
FileSize = myData.GetUInt32(myData.GetOrdinal("filesize"));
rawData = new byte[FileSize];
myData.GetBytes(myData.GetOrdinal("file"), 0, rawData, 0, (int)FileSize);
// must change paths
String desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
fs = new FileStream(#desktopPath + "\\" + myData.GetString("title") + myData.GetString("extension"), FileMode.OpenOrCreate, FileAccess.Write);
myFilePath = desktopPath + "\\" + myData.GetString("title") +myData.GetString("extension");
fs.Write(rawData, 0, (int)FileSize);
fs.Close();
You're looking for the File.Exists() function.
I do not see where you use OpenFileDialog in your code, but you should use SaveFileDialog class for saving files and set it's property CheckFileExists=true
Related
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'm using c#. I'm receiving an error about a path is currently accessed by other processes. What my system is trying to do is to access the path: #"C:\temps\" + client_ids + "_" + rown + ".pdf" and use the same path for attachment before sending it to client's email.
here's what I've done so far. I comment out some of my code because I'm not sure what to do.
FileStream fs = null;
using (fs = new FileStream(#"C:\\temps\\" + client_ids + "_" +
rown + ".pdf",
FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
TextReader tr = new StreamReader(fs);
//report.ExportToDisk
//(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat,tr);
//report.Dispose();
//Attachment files = new Attachment(tr);
//Mailmsg.Attachments.Add(files);
//Clients.Send(Mailmsg);
}
you can make temp copy of file before you use it in mail attachment and then use the copy instead of the original file
You cannot attach a file to an email if that file is open. You must close (save) the file first.
While #ali answer is technically correct, it is unnecessary. Why go through the overhead of creating a copy of the file which then needs to be deleted, etc.?
Assuming I understand what you are trying to do correctly, simply move your code for mail to after the file is successfully created and saved. And, I don't think you need the overhead of either the filestream or the textreader. As long as your report object can save the file to disk someplace, you can attach that file to your email message and then send it.
While I do not claim to know anything about how Crystal Decisions handles exports, etc. Perhaps something like this would work:
(I got this code from: https://msdn.microsoft.com/en-us/library/ms226036(v=vs.90).aspx)
private void ExportToDisk (string fileName)
{
ExportOptions exportOpts = new ExportOptions();
DiskFileDestinationOptions diskOpts =
ExportOptions.CreateDiskFileDestinationOptions();
exportOpts.ExportFormatType = ExportFormatType.RichText;
exportOpts.ExportDestinationType =
ExportDestinationType.DiskFile;
diskOpts.DiskFileName = fileName;
exportOpts.ExportDestinationOptions = diskOpts;
Report.Export(exportOpts);
}
You will need to change the ExportFormatType property.
Then, simply attach the file to your email and send:
Attachment Files = new Attachment(filename);
Mailmsg.Attachments.add(files);
Clients.Send(Mailmsg);
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.
My File is always named like the path and my additional informations i want to have in the Filename but why is it like that?
The Path should be the chosen folder and i want to create a folder then, how can i add a folder than and say + that folder path?
The file is also always created 1 layer above the one i want. For example: C:\Test but the file is saved then in C:\ instead of C:\Test.
public static string path= string.Empty;
string fileName = DateTime.Now.ToString("yyyy.MM.dd") + "test.txt";
try
{
FileStream fs = new FileStream(path + fileName, FileMode.CreateNew, FileAccess.ReadWrite);
StreamWriter sw= new StreamWriter(fs);
sw.WriteLine("Test and so on ..");
}
catch(Exception ex) { }
Rather than using string concatenation, use Path.Combine. Aside from anything else, that will be portable if you ever want to use Mono, too.
Oh, and there are simpler ways to create a text file too:
using (var writer = File.CreateText(Path.Combine(path, fileName))
{
writer.WriteLine(...);
}
Finally, I'd strongly advise using - instead of . in your filename, so that anything which looks at the first . and expects the rest to be an extension doesn't get confused:
string fileName = DateTime.ToString("yyyy-MM-dd") + "-test.txt";
I would like to WRITE to my HTML file in the ASSETS folder.
Please note because my HTML is related to other FILES/FOLDERS i cannot use the personal folder. I must write at the
Assets/HTML/mycharts.html
[MY WRITING code below return these errors
System.IO.File.WriteAllText("file:///android_asset/myGraphs/BarGraph.html", s);
]
ERRORS
UNHANDLED EXCEPTION: System.IO.DirectoryNotFoundException: Could not find a part of the path "//file:///android_asset/myGraphs/BarGraph.html".
at System.IO.FileStream..ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int,bool,System.IO.FileOptions) <0x00208>
at System.IO.FileStream..ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare) <0x00057>
at System.IO.StreamWriter..ctor (string,bool,System.Text.Encoding,int) <0x00087>
at System.IO.StreamWriter..ctor (string,bool,System.Text.Encoding) <0x00037>
at
]
It is not possible to write to the assets folder or edit any files in there. It is read-only.
EDIT:
As suggested in the comments is to initially have your HTML in your assets and when needed they will be saved either on the SD card or in the private storage.
For storing files on SD card you can get the path to the SD card like so:
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "MyAppFolder";
"MyAppFolder" can be anything you want it to be, as long as it does not clash with some of the other folder names on the SD card, so make sure to check if it exists already. Combine that with a file name like so:
var extFileName = folder + Java.IO.File.Separator + "MyFile.txt";
Now write something to the file:
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
using (var fs = new FileStream(extFileName, FileMode.OpenOrCreate))
{
var buf = Encoding.ASCII.GetBytes("Hello, world!");
fs.Write(buf, 0, buf.Length);
}
If you want to store data in the internal storage you can get the path to the private storage with:
var folder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
I achieved this based off the above solution with this code:
using (StreamReader sr = new StreamReader( this.contextCalledFrom.Assets.Open("pdfreport.html")))
html = sr.ReadToEnd();
MemoryStream memoryStream = new MemoryStream();
client.convertHtml(html, memoryStream);
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "wpfolder";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var extFileName = folder + Java.IO.File.Separator + "report.pdf";
using (FileStream file = new FileStream(extFileName, FileMode.Create, FileAccess.Write))
{
memoryStream.WriteTo(file);
}