How do you save and preview an HTML file from temp folder? - c#

I'm developing an HTML editor in C# where you can edit your code in the FastColoredTextBox.dll component. You will have this option in the MenuStrip called "Preview in browser" and there will be a drop down item called "Chrome" and "Iexplore" etc. I want it instead of saving the file, i want it to make a file in the Temp folder and preview it. and after we've modified the code again, the file will update as we preview it again. This is what i have so far:
string location = null;
string sourcecode = FastColoredTextBox1.Text;
location = System.IO.Path.GetTempPath() + "\\TempSite.html";
using (StreamWriter writer = new StreamWriter(location, true))
{
writer.Write(sourcecode);
writer.Dispose();
}
try
{
System.Diagnostics.Process.Start("chrome.exe", location);
}
catch (Exception ex)
{
Interaction.MsgBox(ex.Message);
}
How do you achieve this?

Q: How do you save and preview an HTML file from temp folder?
A: You're already doing precisely that :)
Q: Why does my browser keep re-displaying the original image?
A: Because your browser is reading the html from cache.
SOLUTION:
Give your new file a different name. For example:
location = System.IO.Path.GetTempPath() + Path.GetTempFileName() + ".html";
... OR ...
location = Path.GetTempPath() + Guid.NewGuid().ToString() + ".html";
You can also simply hit <F5> to refresh, <Ctl-Shift-Del> to clear cache, or disable cache in your browser.

Related

How to delete the last character of a file with C#

Hello I'm beginner with C# and I want to delete the last character of my file to inject JSON objects to this file manually (I know that's not the best way to do that), so I can get the right format I tried with multiple ways like open the file, manipulating the string (deleting the last character) and when I try to replace the text in that same file I have errors like IOException: The process cannot access the file 'file path' because it is being used by another process or System.UnauthorizedAccessException : 'Access to the path 'C:\Users\ASUS\Desktop\Root' is denied.
I'll show you the code :
StoreLogs Log = new StoreLogs()
{
Id = ID,
DateTime = dateT,
TaskName = task,
SrcAddress = srcPath,
DstAddress = path,
FileSize = DirSize(new DirectoryInfo(srcPath)),
DelayTransfer = ts.Milliseconds,
};
// Record JSON data in the variable
string strResultJson = JsonConvert.SerializeObject(Log);
// Show the JSON Data
// Console.WriteLine(strResultJson);
// Write JSON Data in another file
string MyJSON = null;
string strPath = #"C:\Users\ASUS\Desktop\Backup\logs\log.json";
if (File.Exists(strPath))
{
//FileInfo table = new FileInfo(strPath);
//string strTable = table.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//Console.WriteLine(erase);
//StreamReader r1 = new StreamReader(strPath);
//string strTable = r1.OpenText().ReadToEnd();
//string erase = strTable.Remove(strTable.LastIndexOf(']'));
//r1.Close();
using (StreamReader sr = File.OpenText(strPath))
{
string table = sr.ReadToEnd();
string erase = table.Remove(table.LastIndexOf(']'));
sr.Close();
File.WriteAllText(strPath, erase);
}
//MyJSON = "," + strResultJson;
//File.AppendAllText(strPath, MyJSON + "]");
//Console.WriteLine("The file exists.");
}
else if (!File.Exists(strPath))
{
MyJSON = "[" + strResultJson + "]";
File.WriteAllText(strPath, MyJSON);
Console.WriteLine("The file doesn't exists.");
}
else
{
Console.WriteLine("Error");
}
// End
Console.WriteLine("JSON Object generated !");
Console.ReadLine();
And that's the result I want :
[{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0},{"Id":"8484","DateTime":"26 novembre 2019 02:33:35 ","TaskName":"dezuhduzhd","SrcAddress":"C:\\Users\\ASUS\\Desktop\\Root","DstAddress":"C:\\Users\\ASUS\\Desktop\\Backup","FileSize":7997832.0,"DelayTransfer":0.0}]
Edit :
Thank you all for your advices
Solution:
FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
fs.SetLength(fs.Length - 1);
fs.Close();
In the code example you have posted you are opening a stream to read the file. A using block will dispose the stream after you exit the block. You are trying to write to the file, while the read stream is still accessing it (the read stream still exists). You've basically opened the file, you read from it, and are trying to write back to it while still holding it open. The reason this is a problem is that you are not using the stream to write. So your second, write, process is unable to access the file. I see you are closing the stream prior to write, but I'm willing to bet it's still holding the reference open.
I would try this method:
How to both read and write a file in C#
what it says is the access to the path (C:\Users\ASUS\Desktop\Root) denied for the user who is running the application. for ex: If you are running from Visual studio on user1 windows login then user1 should have appropriate rights to that root folder. If the code is running by itself (exe) then check the access for that user who is invoking that exe.
Based on the errors you posted seems that:
Maybe you're leaving some stream open pointing to the file you want to edit, use the 'using' statement to avoid this (see this link for more info)
You're trying to access a file when you don't have needed permissions (you aren't a system admin or file is read-only), try changing file ubication or setting it to be writeable (see this link for mor info about the UnauthorizedAccessException exception)
Hope this helps you!

How to read in a file from anywhere (relative path)

I am currently writing a language translator application. I want to support the ability to choose a file, read in the contents of the file into the entry box, and output the translation once the appropriate button is pressed.
I am using the plugin 'Xam.Plugin.FilePicker' to allow the user to choose a file, which is working. When the user chooses a file, I have it so that the name of the file is displayed on the screen. However, problems occur when trying to read in the file into the entry box, which I believe is linked to the application not being able to determine the path of the file - currently the application tries to read in the file from the location where Visual Studio 2017 is located.
I have tried several approaches, some of which are detailed in the below:
How to get relative path of a file in visual studio?
How to read from a file using C# code?
I have also tried:
var file = await CrossFilePicker.Current.PickFile();
if (file != null) {
string filePath =
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string filename = Path.Combine(filePath, file.FileName);
using (var reader = new StreamReader(filename)) {
entText= reader.ReadToEnd();
}
}
Where entText is the name of the entry box in the MainPage.xaml.cs file
Below is the code I have so far. I have removed the above code from the file and, while it was giving me a path, the path was either the path in which Visual Studio 2017 is located in or some other path. Either way, the application couldn't find the file.
C# code:
private async void BtnReadFile_Clicked(object sender, EventArgs e)
{
string fileName;
string fileText;
string filePath;
// Allows the user to choose a file from any location
var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
lblFileRead.Text = file.FileName; // Displays the name of the file
}
}
Xaml code:
Entry box:
<Entry x:Name="entText" Placeholder="Enter text to translate" Keyboard="Text"
HeightRequest="200" WidthRequest="250" TextChanged="EntText_TextChanged" />
Button to read in file
<Button x:Name="btnReadFile" Text="Read in file" Clicked="BtnReadFile_Clicked" />
To conclude, I want to be able to read in a file from any location, not just a predetermined location i.e.
The user should be able to read in a file from "C:/Documents/files", "C:/Downloads/", etc.
I guess you are using Xamarin? You are not supposed to have access to the file itself. You can get the name and you can get the contents.
You can get the file's contents by accessing file.DataArray instead of using the traditional file access. So what the actual path of the file is, is none of your business.
the CrossFilePicker returns a full path reference to the selected file. So you don't have to combine it with any other path.
Refer to the example from the project website
It shows exactly what you try to do - read the file content and output it.
try
{
FileData fileData = await CrossFilePicker.Current.PickFile();
if (fileData == null)
return; // user canceled file picking
string fileName = fileData.FileName;
string contents = System.Text.Encoding.UTF8.GetString(fileData.DataArray);
System.Console.WriteLine("File name chosen: " + fileName);
System.Console.WriteLine("File data: " + contents);
}
catch (Exception ex)
{
System.Console.WriteLine("Exception choosing file: " + ex.ToString());
}
You just have to replace the Console output by putting the value of contents to your control.
You are setting filePath to
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
when it should instead be:
file.FilePath
since the latter is the actual location of the file.

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

Writing to text files using SaveFileDialog

I'm working on an Add In for Microsoft Excel in Visual Studio that records the balances for each account (or Worksheet) and saves them to a user-specified file. The ability to press a button and select a destination to save your work is an essential skill for any programmer, so I'm perplexed as to why there is so little information on how to do it. The closest thing I found was a tutorial on MSDN that saves a button icon image.
The code I'm currently using is as follows:
StringBuilder sb = new StringBuilder();
if (ThisAddIn.createdbudget)
{
string budget = "Budget = " + ThisAddIn.blake.budget;
SaveFileDialog savebudget = new SaveFileDialog();
savebudget.Filter = "Data files (*.dat)|*.dat|All files (*.*)|*.*";
savebudget.Title = "Save Budget";
savebudget.ShowDialog();
if (savebudget.FileName != "")
{
using (StreamWriter sr = new StreamWriter(savebudget.OpenFile()))
{
sb.AppendLine(budget);
}
}
}
else
{
MessageBox.Show("Control disabled. Budget does not yet exist.");
}
My objective is to allow the user to designate a file path via SaveFileDialog and save a new .dat (or .txt). The stream writer would record the account names and their respective balances line by line. Something like:
sr.WriteLine(Account1.Name + " Balance = " + Account1.Balance);
sr.WriteLine(Account2.Name + " Balance = " + Account2.Balance);
etc...
I know this sounds complicated. I have no problem saving data if I'm using a predetermined file path, but that's not very helpful. What I need to know is how to properly write files using SaveFileDialog.

File Uploading using Server.MapPath() and FileUpload.SaveAs()

I have a website admin section which I'm busy working on, which has 4 FileUpload controls for specific purposes. I need to know that , when I use the Server.MapPath() Method Within the FileUpload control's SaveAs() methods, Will it still be usable on the web server after I have uploaded the website? As far as I know, SaveAs() requires an absolute path, that's why I map a path with Server.MapPath()
if (fuLogo.HasFile) //My FileUpload Control : Checking if a file has been allocated to the control
{
int counter = 0; //This counter Is used to ensure that no files are overwritten.
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]); // This is the part Im wondering about. Will this still function the way it should on the webserver after upload?
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++; //Here the counter is put into action
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
if (fuLogo.PostedFile.ContentLength > 409600 ) //File must be 400kb or smaller
{
cvValidation.ErrorMessage = "Please use a picture with a size less than 400 kb";
cvValidation.IsValid = false;
}
else
{
if (fuLogo.HasFile && cvValidation.IsValid)
{
fuLogo.SaveAs(logo); //Save the logo if file exists and Validation didn't fail. The path for the logo was created by the Server.MapPath() method.
}
}
}
else
{
logo = "N/A";
}
If you intend to save the files in
a directory on your web server , then
the Server.MapPath() will be the suitable
solution.
string dirPath = System.Web.HttpContext.Current.Server.MapPath("~") + "/Images/Logos/"+ fileBreak[0] + counter.ToString() + "." + fileBreak[1];
Look Here
if you intend to save your files out
the web server then
Use a full path, like "c:\uploads"
and be sure that the web process has
permission to write to that folder,I suggest you store the path itself in the web.config file in this case.
yes, that can be used after saving file and when you try retrieve that file...
Server.MapPath("~/Images/Logos/" + uploadedFileName);
Yes it should still work as Server.MapPath uses the relative values and returns the complete physical path.
It's one line of code:
FileUpload1.PostedFile.SaveAs(Server.MapPath(" ")+"\\YourImageDirectoryOnServer\\"+FileUpload1.FileName);

Categories

Resources