How to open excel file's read only mode on C#? - c#

I'm creating dataset from csv excel file and that files is processing while I access it.
It says "
I need to access it read only mode? This is working code.
private void connect()
{
try
{
if (checkbox1.Checked == false)
{
FilePath = #"C:\FILE";
}
else
{
FilePath = #"\\192.168.0.2\file\"; //
}
strConn = #"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + FilePath + #"\;Extensions=csv,txt";
Connect = new OdbcConnection(strConn);
Connect.Open();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
DataGrid1.SelectAll();
DataGrid1.ClearSelection();
FileName = ".csv";
CSVDataSource = FilePath + FileName;
ReadData(FileName);
DataGrid1.Update();
}

It says it cannot open the file '(unknown)'. The thing about exclusive and permissions is probably just a too general error description. You do not seem to have a valid file path, also you might not be able to open it directly from a network path.
Verify your file path, and if it still not works - copy it to your local machine and try again.

Related

Creating a new directory for log event file in windows service in c#

I am wondering on how to create a new directory for a log event file in windows service through c#
I have the following code:
public static void WriteLog(string Message)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\DataFile.txt", true);
//sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "C:\\MulpuriServiceLOG\\data.txt", true);
//sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
sw.WriteLine(Message);
sw.Flush();
sw.Close();
}
catch{}
}
As the docuemtation states for the Directory.CreateDirectory(path):
Creates all directories and subdirectories in the specified path unless they already exist.
Modified from the example source code:
string path = #"c:\MyDir";
try
{
// Try to create the directory.
Directory.CreateDirectory(path);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
There is a really great tutorial on dotnetperls containing example code, exceptions, tips and other useful information about creating directories!
Look up that SO-question to create folders inside the same directory your executable has started, or simple use relative paths instead of absolute ones:
Directory.CreateDirectory("Test");
That way you will never have conflicts about finding the correct path!
File yourFolder= new File("C:/yourFolder");
// if the directory does not exist, create it
if (!yourFolder.exists()) {
System.out.println("Creando directorio: " + yourFolder.getName());
boolean result = false;
try
{
yourFolder.mkdir();
result = true;
}
catch(SecurityException se){
}
if(result) {
System.out.println("Folder created");
}
}

How to delete file from isolated Storage

I am trying to delete files from isolated storage. But it returning error message to me. I don't know where i did mistake.
public void Delete(string folder, string fileName)
{
try
{
string path = folder + "\\" + fileName + ".txt";
string delPath = folder + "/" + fileName + ".txt";
MessageBox.Show(delPath);
if (myIsolatedStorage.DirectoryExists(folder))
{
if (myIsolatedStorage.FileExists(delPath))
{
myIsolatedStorage.DeleteFile(delPath);
MessageBox.Show("File is Deleted..!!");
}
else
MessageBox.Show("There is no file is exists");
}
else
{
MessageBox.Show("There is no Folder is exists");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Please let me know where i did mistake.
Thanks in advance..
Error message:-
Perhaps, the file, you're trying to delete, is still in usage. Your application should have no open files or references to files that you are trying to delete.

How to create a folder then save an image to the created folder using fileuploader in C# asp.net?

I have a simple program here wherein I can create a folder then save the an image to the folder created. The folder gets successfully created but I'm getting error into saving it to the newly created file. The error is:
The file could not be uploaded. The following error occured: 'N:/Kim's New Project/Safety Accident Report/File Uploader 2/File
Uploader 2/Uploads/asdsa' is a physical path, but a virtual path was
expected.
Can you please check my code. Please help. Thank you.
protected void button1_Click(object sender, EventArgs e)
{
if (FileUpload2.HasFile)
{
try
{
if (FileUpload2.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload2.PostedFile.ContentLength < 512000)
{
string strpath = #"N:\Kim's New Project\Safety Accident Report\File Uploader 2\File Uploader 2\Uploads\" + txtName.Text;
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
lblResult.Text = "Directory Created";
if ((Directory.Exists(strpath)))
{
string filename = Path.GetFileName(FileUpload2.FileName);
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
Label1.Text = "File uploaded successfully!";
}
}
else
{
lblResult.Text = "Already Directory Exists with the same name";
}
}
else
Label1.Text = "File maximum size is 500 Kb";
}
else
Label1.Text = "Only JPEG files are accepted!";
}
catch (Exception exc)
{
Label1.Text = "The file could not be uploaded. The following error occured: " + exc.Message;
}
}
Instead of
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
try
FileUpload2.SaveAs(Path.Combine(strPath, filename));
you already know the physical save path - no need for Server.MapPath
Try..
string strpath = Server.MapPath("~/Test");
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
}

To delete a desk top file in asp.net c#

i want a solution for this , i want to delete a file which is residing in my desk top using asp.net c# , i used below code:
try
{
FileInfo TheFile = new FileInfo(MapPath(".") + "\\" + FileNameTextBox.Text);
if (TheFile.Exists)
{
File.Delete(MapPath(".") + "\\" + FileNameTextBox.Text);
}
else
{
throw new FileNotFoundException();
}
}
catch (FileNotFoundException ex)
{
lblStatus.Text += ex.Message;
}
catch (Exception ex)
{
lblStatus.Text += ex.Message;
}
but it always says the file location cannot be found , please help me
thanks in advance `
If you are trying to delete a user's desktop file using an asp .net page you cannot do it. The code executes on the server side and the path will access to the desktop of the server that your application is being hosted.
I would try doing it this way instead:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
File.Delete(Path.Combine(desktopPath, "filetobedeleted"));

C# linq Files.ReadAllLines() fails for large 650MB CSV file

The following code works when I work with CSV files under 1MB but fails when I try to read 600MB file. Any reason why? Or any fixes?
What I am trying to do is read a large raw CSV file in Visual C# 2010 and manipulate the contents, could be line by line or to memory at one go and export 5 files with certain selections using LINQ. These 5 files are to be used in various processes so need them to be split into 5 different files with very different content.
When the file is small the codes work perfect but when it's too big it gives me the messagebox from Exception handling "Cannot write to source destination". I have tried both ReadAllLines() and ReadLines() Please could you advise me. Thanks.
public void button2_Click(object sender, EventArgs e)
{
string file_name = textBox1.Text.ToString();
// Get the directories to split the file in.
string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString());
if (File.Exists(file_name) == true)
{
try
{
StreamReader readerfile = new StreamReader(file_name);
var BillSummaryQuery1 =
(from line in File.ReadAllLines(file_name)
let linerecord = line.Split(',').ToList()
select line).ToList();
#region Start Writing BillSummary.CSV
//lines removed
#endregion End writing BillSummary.CSV
#region Start writing Notes.CSV
//lines removed
#endregion Notes.CSV
string message =
"Bill Translated Successfully! \r\nFiles located in: " + directoryPath;
MessageBox.Show(message, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
string message2 = "Cannot write to source destination";
MessageBox.Show(message2, "Error");
}
}
else
{
MessageBox.Show("No such file exists","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
If you are using a StreamReader, why don't use it ?
public void button2_Click(object sender, EventArgs e)
{
string file_name = textBox1.Text.ToString();
// Get the directories to split the file in.
string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString());
if (File.Exists(file_name) == true)
{
try
{
using (StreamReader reader= new StreamReader(file_name))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
// Do your stuff
}
}
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
string message2 = "Cannot write to source destination";
MessageBox.Show(message2, "Error");
}
}
else
{
MessageBox.Show("No such file exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Rolling your own CSV reader is a waste of time unless the files that you're reading are guaranteed to be very simple. Use a pre-existing, tried-and-tested implementation instead.

Categories