In my project i need to create an excel file in users desktop. Code written in my visual studio is.
string sPathTestData1 = "\\AdaptiveModulations.xls";
string sPathTestData = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\AdaptiveModulations" + sPathTestData1;
string sheet = "Sheet1";
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\AdaptiveModulations";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
ExcelUtils.createExcelFile(sPathTestData,sheet);
}
else
{
ExcelUtils.setExcelFile(sPathTestData,sheet);
}
This code is working perfectly in my system and creating folder with excel file but when i copied the exe from C:\Visual Studio 2015\Projects\AMCalculator\AMCalculator\bin\Debug folder and saved in another machine it showing error can anyone help on this
I have added try/catch blocks in my classes
In ExcelUtils Class :
public static void createExcelFile(String filepath, String sheetName)
{
try
{
using (FileStream stream = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite))
{
workBook = new HSSFWorkbook();
workSheet = workBook.CreateSheet(sheetName);
workBook.Write(stream);
stream.Close();
}
}
catch (Exception e) {
Console.WriteLine("Unable to Create File. Exception is : " + e);
}
}
public static void setExcelFile(string filepath, string sheetName)
{
try
{
Console.WriteLine("File Path is : " + filepath);
workBook = WorkbookFactory.Create(new FileStream(
Path.GetFullPath(filepath),
FileMode.Open, FileAccess.Read,
FileShare.ReadWrite));
workSheet = workBook.GetSheet(sheetName);
}
catch (Exception e)
{
Console.WriteLine("Unable to Load File. Exception is : " + e);
}
}
In My main class :
if (!File.Exists(sPathTestData))
{
Directory.CreateDirectory(path);
try
{
ExcelUtils.createExcelFile(sPathTestData, sheet);
}
catch (FileNotFoundException fe)
{
Console.WriteLine("Unable to Create File. Exception is : " + fe);
}
}
else
{
try
{
ExcelUtils.setExcelFile(sPathTestData, sheet);
}
catch (FileNotFoundException fe)
{
Console.WriteLine("Unable to Load File. Exception is : " + fe);
}
}
Related
Every time I click on a file, I get the error
Empty path name is not legal
I need a user to upload a .txt or .csv file and have the contents of that file to display in the data grid view. Everything works fine except for this one error that occurs on this line:
var sr = new StreamReader(openFileDialog1.FileName);
Full code.
private void selectButton_Click (object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
var sr = new StreamReader(openFileDialog1.FileName);
SetText(sr.ReadToEnd());
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message{ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
}
try to add filter on openFileDialog1 like.
openFileDialog1.Filter = "text file(*.txt)|*.txt|csv file(*.csv)|*.csv";
Check the FileName before open file:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (string.IsNullOrEmpty(openFileDialog1.FileName) {
// ..
return;
}
try
{
var fileStream = openFileDialog1.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
SetText(sr.ReadToEnd());
}
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message{ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
I'm writing a windows service (C#) that does a task repetitively. I'm using a thread to complete my requirement. Now I need to maintain a log file that keeps logs regarding the operation.
My service class is as follow
public partial class CPEService : ServiceBase
{
static ServiceBot bot = new ServiceBot();
static ProgramLog logger = new ProgramLog();//ProgramLog Object
private static bool state = true;
//private static int count = 1;
//private System.Timers.Timer timer;
public CPEService()
{
InitializeComponent();
}
internal void TestStartupAndStop()
{
Thread workerThread = new Thread(loopTrough);
workerThread.Start();
}
protected override void OnStart(string[] args)
{
Thread workerThread = new Thread(loopTrough);
workerThread.Start();
}
private void loopTrough()
{
logger.log("Thread fired");
while (state)
{
logger.log("Thread fired"); //This is not Working
bot.start();
Thread.Sleep(180000);
}
}
protected override void OnStop()
{
state = false;
}
}
I have a separate class call "ProgramLog" to handle all the log related operations.This is that class.
public class ProgramLog
{
string fileName = "";//Global variable to store file name
#region method to handle usual log records
public void log(string text)//create normal Log text
{
fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory+fileName))
{
using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine(text);
tw.Flush();
tw.Close();
fs.Close();
}
}
else
{
createFolder();
log(text);
}
}
#endregion
#region log Error record
public void logError(string text, string className,int LineNumber, string Stacktrace)//create error text
{
fileName = "Log\\" + DateTime.Now.Date.ToString("d").Replace('/', '_') + ".txt";
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + fileName))
{
using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Append))
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine("**************************ERROR****************************");
tw.WriteLine(text);
tw.WriteLine("In Class :{0}", className);
tw.WriteLine("In Line :{0}", LineNumber);
tw.WriteLine("ERROR :{0}",Stacktrace);
tw.WriteLine("***********************************************************");
}
}
else
{
createFolder();
logError(text,className,LineNumber,Stacktrace);
}
}
#endregion
#region create folder to store log files
public void createFolder()//create a folder for Log files
{
try
{
if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "Log"))
{
string folderName = "Log";
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + folderName);
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
StreamWriter sr = new StreamWriter(fs);
sr.Flush();
sr.Close();
fs.Close();
}
else
{
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create);
StreamWriter sr = new StreamWriter(fs);
sr.Flush();
sr.Close();
fs.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
#endregion
}
According to the above class, When I start the service it needs to create folder call "Log" where it does not exists, then it creates a text file inside that folder and lastly it starts to create the log entries.
Even though the thread is working correctly it never touches the "ProgramLog" methods. I checked by directly calling the method "loopTrough". then its working fine.
Please help me to resolve this bug.
Thank you
You declare a Thread workerThread = new Thread(loopTrough);, but you don't start this Thread. Just call workerThread.Start().
I have been trying to log exceptions to a file. I can get the exception with all its details and when I step through the class the StreamWriter logWriter doesn't seem to do what I thought it would do.
public static void Write(Exception exception)
{
string logfile = String.Empty;
try
{
logfile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLog"]).ToString();
StreamWriter logWriter;
if (File.Exists(logfile))
{
logWriter = File.AppendText(logfile);
}
else
{
logWriter = File.CreateText(logfile);
logWriter.WriteLine("=>" + DateTime.Now + " " + " An Error occurred: " + exception.StackTrace +
" Message: " + exception.Message + "\n\n");
logWriter.Close();
throw exception;
}
}
catch (Exception e)
{
throw;
}
}
I would of thought the logWriter would of written the exception details to the File.AppendText(logfile)but it doesn't and just jumps straight out the if statement. All the details of the exception are in the else statement, I have tried to put this in theif` condition but throws an exception!
How can I write the exception to the file. I got the code from CodeProject. Everything thing works fine except writing the exception to the file.
Try it correctly and throw the exception outside of the method:
public static void Write(Exception exception)
{
string logfile = String.Empty;
try
{
logfile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ErrorLog"]).ToString();
if(File.Exists(logfile))
{
using(var writer = new StreamWriter(logfile, true))
{
writer.WriteLine(
"=>{0} An Error occurred: {1} Message: {2}{3}",
DateTime.Now,
exception.StackTrace,
exception.Message,
Environment.NewLine
);
}
}
}
catch(Exception e)
{
throw;
}
}
Throw it outside:
catch(Exception e)
{
Write(e);
throw;
}
This snippet works to write into a file
public static bool WriteResult(string result)
{
using (StreamWriter sr = File.AppendText("result.txt"))
{
sr.WriteLine(result);
sr.Flush();
return true;
}
return false;
}
For you, you have to adapt it a bit to meet your requirments :
public static void Write(Exception exception) {
try {
using(StreamWriter sr = File.AppendText("result.txt")) //new StreamWriter("result.txt", Encoding. ))
{
sr.WriteLine("=>" + DateTime.Now + " " + " An Error occurred: " + exception.StackTrace +
" Message: " + exception.Message + "\n\n");
sr.Flush();
}
catch (Exception e) {
throw;
}
}
A nice template method i wrote goes with every project.
private static void AddLog(string strMsg)
{
#region logfolder creation
if (!System.IO.Directory.Exists("C:\\appname"))
{
System.IO.Directory.CreateDirectory("C:\\appname");
if (!System.IO.Directory.Exists("C:\\appname\\Logs"))
{
System.IO.Directory.CreateDirectory("C:\\appname\\Logs");
}
}
#endregion
#region logfile creation
FileStream fsc;
logFileName = "C:\\appname\\Logs\\appnameLog_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".txt";
if (!System.IO.File.Exists(logFileName))
{
fsc = new FileStream(logFileName, FileMode.Create, FileAccess.Write);
fsc.Close();
}
#endregion
#region logging
using (FileStream fs = new FileStream(logFileName, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sr = new StreamWriter(fs))
{
try
{
sr.WriteLine(strMsg);
}
catch (Exception exc)
{
EventLogEntry(exc.ToString().Trim(), EventLogEntryType.Error, 7700);
}
}
}
#endregion
}
I had developed a filewatcher program to monitor a folder, if there are any changed of the file, it will copy the file to another folder.
But I found that there will be error message when writing the original file (e.g. file being prcoess by another application...) it seems that the file locked when running [System.IO.File.Copy] copying to another folder.
Is there any solution can avoid the original file locked by the filewatcher/System.IO.File.Copy? Thanks.
The following is my code:
private void fileWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
if (lastWriteTime != lastRead)
{
txtLog.Text += e.ChangeType + ": " + e.FullPath + "\r\n";
txtLog.Focus();
txtLog.Select(txtLog.TextLength, 0);
txtLog.ScrollToCaret();
try
{
string myPath = e.FullPath;
string myFile = e.Name;
System.IO.FileInfo myFileInfo = new System.IO.FileInfo(myFile);
string myAttibs = myFileInfo.Attributes.ToString();
System.IO.File.Copy(myPath, #"D:\\Folder\\Output\\" + myFile, true);
lastRead = lastWriteTime;
}
catch (System.IO.IOException ex)
{
System.IO.IOException myex = ex;
}
catch (System.Exception ex)
{
System.Exception myex = ex;
}
}
}
I ran into the same problem. I am not fond of my solution, as it feels hackish. But it works:
FileSystemWatcher fsWatcher = new FileSystemWatcher();
fsWatcher.Created += new FileSystemEventHandler( fsWatcher_Created );
private void fsWatcher_Created( object sender, FileSystemEventArgs e )
{
RaiseFileFoundEvent( e.FullPath );
while ( !TestOpen( e.FullPath ) ) ;
RaiseFileCopyDoneEvent( e.FullPath );
}
private bool TestOpen( string filename )
{
try
{
FileStream fs = new FileStream( filename, FileMode.Open,
FileAccess.Write, FileShare.None );
fs.Close();
return true;
}
catch ( Exception )
{
return false;
}
}
private void RaiseFileFoundEvent( string fullPath )
{
// a file is found, but the copy is not guaranteed to be finished yet.
}
private void RaiseFileCopyDoneEvent( string fullPath )
{
// the file is found, and we know the copy is done.
}
There's not a good way to solve this problem. How should the program behave if you're in the middle of copying the file to a new location when another application wants to write to it?
If you're willing to copy a corrupted file (that was written-to while you were copying), you'll have to write your own Copy method that uses FileShare.ReadWrite.
I am making a module that shows the tree view of documents that are stores on my drive in a folder. It is retrieving well. But the problem is that the documents are in different format like(.pdf, .docx etc). That are not opening in browser on click. There it shows a 404.4 error. So Tell me how can I download/open different format files through button click? The following is my code:
protected void Page_Load(System.Object sender, System.EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
if (Settings["DirectoryPath"] != null)
{
BindDirectory(Settings["DirectoryPath"].ToString());
}
else
{
BindDirectory(Server.MapPath("~/"));
}
}
}
catch (DirectoryNotFoundException DNEx)
{
try
{
System.IO.Directory.CreateDirectory("XIBDir");
BindDirectory(Server.MapPath("XIBDir"));
}
catch (AccessViolationException AVEx)
{
Response.Write("<!--" + AVEx.Message + "-->");
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
#endregion
#region Optional Interfaces
/// -----------------------------------------------------------------------------
/// <summary>
/// Registers the module actions required for interfacing with the portal framework
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <history>
/// </history>
/// -----------------------------------------------------------------------------
public ModuleActionCollection ModuleActions
{
get
{
ModuleActionCollection Actions = new ModuleActionCollection();
Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
return Actions;
}
}
#endregion
private void BindDirectory(string Path)
{
try
{
System.IO.DirectoryInfo dirRoot = new System.IO.DirectoryInfo(Path);
TreeNode tnRoot = new TreeNode(Path);
tvDirectory.Nodes.Add(tnRoot);
BindSubDirectory(dirRoot, tnRoot);
tvDirectory.CollapseAll();
}
catch (UnauthorizedAccessException Ex)
{
TreeNode tnRoot = new TreeNode("Access Denied");
tvDirectory.Nodes.Add(tnRoot);
}
}
private void BindSubDirectory(System.IO.DirectoryInfo dirParent, TreeNode tnParent)
{
try
{
foreach (System.IO.DirectoryInfo dirChild in dirParent.GetDirectories())
{
//TreeNode tnChild = new TreeNode(dirChild.Name);
TreeNode tnChild = new TreeNode(dirChild.Name, dirChild.FullName);
tnParent.ChildNodes.Add(tnChild);
BindSubDirectory(dirChild, tnChild);
}
}
catch (UnauthorizedAccessException Ex)
{
TreeNode tnChild = new TreeNode("Access Denied");
tnParent.ChildNodes.Add(tnChild);
}
}
private void BindFiles(string Path)
{
try
{
tvFile.Nodes.Clear();
System.IO.DirectoryInfo dirFile = new System.IO.DirectoryInfo(Path);
foreach (System.IO.FileInfo fiFile in dirFile.GetFiles("*.*"))
{
string strFilePath = Server.MapPath(fiFile.Name);
string strFilePaths = "~/" + fiFile.FullName.Substring(15);
TreeNode tnFile = new TreeNode(fiFile.Name, fiFile.FullName, "", strFilePaths, "_blank");
tvFile.Nodes.Add(tnFile);
}
}
catch (Exception Ex)
{
Response.Write("<!--" + Ex.Message + "-->");
}
}
protected void tvDirectory_SelectedNodeChanged(object sender, EventArgs e)
{
try
{
string strFilePath = tvDirectory.SelectedNode.Value;
BindFiles(tvDirectory.SelectedNode.Value);
}
catch (Exception Ex)
{
Response.Write("<!--" + Ex.Message + "-->");
}
}
}
}
404.4 means that the web server (IIS presumably) does not now how to serve the file (based on extension). If your code is serving other files correctly, this is a web server configuration issue. Check your servers documentation for adding the appropriate handlers for the file extensions that aren't working.
I would use a hyperlink in your treeview that opens the link: openfile.ashx?path=[insertpathhere] (make sure that your link opens in target="_blank")
within your Generic Handler (ASHX) you have access to load a file from Disk, and stream its bytes into the responseStream. and that will cause the file to download at the browser. You should also set the content-type where applicable.
Code Sample Requested...
Preface: There are some "extra" things going on here... I base64 Encoded the path in my example because I didnt want the path to be 'human-readable'. Also, when I handed it off to the browser I am pre-pending 'export-' plus a timestamp... but you get the idea...
public class getfile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var targetId = context.Request.QueryString["target"];
if (string.IsNullOrWhiteSpace(targetId))
{
context.Response.ContentType = "text/plain";
context.Response.Write("Fail: Target was expected in querystring.");
return;
}
try
{
var url = new String(Encoding.UTF8.GetChars(Convert.FromBase64String(targetId)));
var filename = url.Substring(url.LastIndexOf('\\') + 1);
filename = "export-" + DateTime.Now.ToString("yyyy-MM-dd-HHmm") + filename.Substring(filename.Length - 4);
context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", filename));
var data = File.ReadAllBytes(url);
File.Delete(url);
context.Response.BinaryWrite(data);
}
catch (Exception ex)
{
context.Response.Clear();
context.Response.Write("Error occurred: " + ex.Message);
context.Response.ContentType = "text/plain";
context.Response.End();
}
}
public bool IsReusable { get { return false; } }
}