I just want the directory to open to "project_name\Scripts(sub_folder)\merge.sql"
I can't get rid of 'C:' and I cant get the actually data file to appear.
I received an"System.io.directorynotfoundexcpetion".
Here's my code:
private void MergeQuery()
{
//might need to change C: drive directory
//string derefQuery = #"\.\mergeSQL.sql";
using (SqlConnection mer = new SqlConnection(#"Data Source = address_name; Initial Catalog = catalog_name; Integrated Security=SSPI"))
{
{
mer.Open();
string path = Path.GetDirectoryName("\\project_name\\Scripts\\mergeSQL.sql ");
string mergeScript = System.IO.File.ReadAllText(path);
System.Collections.Generic.IEnumerable<string> commandStrings = Regex.Split(mergeScript, #"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
using (var command = new SqlCommand(commandString, mer))
{
command.ExecuteNonQuery();
}
Label2.Text = "Query merged";
}
}
}
}
first, there is an error in line
string path = Path.GetDirectoryName("\\project_name\\Scripts\\mergeSQL.sql ");
In that line you're getting directory path from file path, so path variable becomes \\project_name\\Scripts\\ or something similar. On next line you're trying to read file from that path variable, not from file.
What you need is to get path relative to web site root and then read file, like this
string path = HostingEnvironment.MapPath("~/Scripts/mergeSQL.sql ");
string mergeScript = System.IO.File.ReadAllText(path);
this way asp.net will get correct path from your website root's subfolder.
Related
I got a folder in C called "donotcopy". I want to protect it and no matter what not to be allowed to create files within.
My intuitive solution was just to create a str with same name and where user enters a destination it just checks if it's the same.
Example:
class FileCreation
{
public static void Main()
{
string notallowed = ("c:\\donotcopy");
string filename = ("Nick.txt");
Console.WriteLine("Enter the full path to create an empty file.");
string path = Console.ReadLine();
path = path.ToLower();
while (notallowed == path)
{
Console.WriteLine("The chosen path is not allowed please try another one.");
path = Console.ReadLine();
path = path.ToLower();
}
using (FileStream fs = File.Create(path + filename)) ;
}
}
The problem is if the user enters the destination as "c:.\donotcopy" it will still create the file inside the restricted folder.
You can make use of the DirectoryInfo class, which will allow you to retrieve info about the full path of a directory.
class FileCreation
{
public static void Main()
{
string notallowed = ("c:\\donotcopy");
string filename = ("Nick.txt");
Console.WriteLine("Enter the full path to create an empty file.");
DirectoryInfo directory = new DirectoryInfo(Console.ReadLine());
while (notallowed.Equals(directory.FullName, StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("The chosen path is not allowed please try another one.");
directory = new DirectoryInfo(Console.ReadLine());
}
string fullPath = Path.Combine(directory.FullName, filename);
using (FileStream fs = File.Create(fullPath)) ;
}
}
I'd like to try the performance of MySqlBulkLoader knowing that the Adapter.update() method i'm using is taking roughly 30 mn to run.
I understand you have to go through a file to do it so here is my code :
private void button14_Click(object sender, EventArgs e)
{
string fileName = #"C:\Users\Utilisateur\ds.txt";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
using (StreamWriter sw = File.CreateText(fileName))
{
foreach (DataRow row in Globals.ds.Tables[0].Rows)
{
foreach (object item in row.ItemArray)
{
string itemstr = item.ToString();
sw.Write((string)itemstr + "\t");
}
sw.WriteLine();
}
}
using (var conn = new MySqlConnection(Globals.connString))
{
conn.Open();
MySqlCommand comm = new MySqlCommand("TRUNCATE Song",conn);
comm.ExecuteNonQuery();
var bl = new MySqlBulkLoader(conn)
{
TableName = Globals.ds.Tables[0].ToString(),
Timeout = 600,
FieldTerminator = "\t",
LineTerminator = "\n",
FileName = fileName
};
var numberOfInsertedRows = bl.Load();
Console.WriteLine(numberOfInsertedRows);
}
}
The file is generated ok. but at the var numberOfInsertedRows = bl.Load(); line, i have the following error at run time :
MySql.Data.MySqlClient.MySqlException: 'Can't get stat of '/var/packages/MariaDB10/target/mysql/disk/C:\Users\Utilisateur\ds.txt' (Errcode: 2 "No such file or directory")'
I tried to put "/" instead of "\" in the fileName but it's the same error.
I have no idea what's going on, anyone can help ?
Thanks
By default, MySqlBulkLoader loads a file from the server's file system. To use a local file, set bl.Local = true; before calling bl.Load().
To enable this, you will need to set AllowLoadLocalInfile = True in your connection string; see https://mysqlconnector.net/troubleshooting/load-data-local-infile/
Finally, if you switch to MySqlConnector, you can use its MySqlBulkCopy API to load data directly from a DataTable, instead of first saving it to a local CSV file, then loading that file.
I have a .csv file as the attached image which has a list of folders and files . I would like to read the .csv file and recreate the same folder structure under different folder.
Say for example I have C:\Data\SourceFolder\Folder2\Folder4\File1.txt , I would like the file to be moved to C:\Data\FilesCopiedfromC\SourceFolder\Folder2\Folder4\File1.txt . In the above destinaton path , the C:\Data\FilesCopiedfromC is going to be the same always . I am able to create the folder structure in the destination but when I do the file.move from source to destination I get a "File cannot be created when it already exists error".
try
{
string inputfile = textBox1.Text.ToString();
using(StreamReader reader = new StreamReader(inputfile))
{
string headerline = reader.ReadLine();
Boolean firstline = true;
string line = string.Empty;
string SourceFileNameCSV;
string SourceFilePathCSV,totalSourceFilePath, strConstructedDestinationfullpath;
string[] parts;
while ((line = reader.ReadLine()) != null)
{
char[] delimiters = new char[] { ',' };
parts= line.Split(delimiters);
if (parts.Length > 0)
{
SourceFilePathCSV = parts[0];
SourceFileNameCSV = parts[1];
totalSourceFilePath = SourceFilePathCSV + "\\" + SourceFileNameCSV;
strDestinationDynamicPath = SourceFilePathCSV.Replace("C:\\Data\\", " ").TrimEnd();
strConstructedDestinationfullpath = Path.Combine(strDestinationStaticPath, strDestinationDynamicPath);
if (!string.IsNullOrEmpty(strConstructedDestinationfullpath))
{
if (!Directory.Exists(strDestinationDynamicPath))
{
Directory.CreateDirectory(strConstructedDestinationfullpath);
}
// File.Move(totalSourceFilePath, strConstructedDestinationfullpath);
}
}
}
}
}//try
Any help is appreciated.
You need to specify a file name for the destination, currently you are just providing a path:
File.Move(
totalSourceFilePath,
Path.Combine(strConstructedDestinationfullpath, Path.GetFileName(totalSourceFilePath));
It's because, apparently, the file already exists in the destination. What you can do is check if the file exists an delete if so:
if (System.IO.File.Exists("filename"))
{
//delete
System.IO.File.Delete("filename"); //try/catch exception handling
needs to be implemented
}
I have an Azure App (.Net 4.5) and I have some static files stored on the filesystem that I want to read from, but I get a System.UnauthorizedAccessException like so
string template = string.Empty;
var file = HostingEnvironment.MapPath("~/App_Data/EmailTemplates/" + fileName);
if (!string.IsNullOrEmpty(file))
{
template = File.ReadAllText(file); <-- Unauthorized Access Exception Here
}
return template;
I know the best practice is Azure Storage, but how do I make this work this way?
As File.ReadAllText states about UnauthorizedAccessException, it could be caused by one of the following conditions:
path specified a file that is read-only.
-or-
This operation is not supported on the current platform.
-or-
path specified a directory.
-or-
The caller does not have the required permission.
You could leverage kudu console and use Attrib command to check the attributes for your files or directories. Also, you could try to use TYPE command to display the contents of your file or click the Edit button from the file list table as follows:
Also, I created a new web app and deployed my MVC application for displaying the files under the App_Data folder, it could work as expected, you could refer to it.
UPDATE:
//method for getting files
public List<DownLoadFileInformation> GetFiles()
{
List<DownLoadFileInformation> lstFiles = new List<DownLoadFileInformation>();
DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/App_Data"));
int i = 0;
foreach (var item in dirInfo.GetFiles())
{
lstFiles.Add(new DownLoadFileInformation()
{
FileId = i + 1,
FileName = item.Name,
FilePath = dirInfo.FullName + #"\" + item.Name
});
i = i + 1;
}
return lstFiles;
}
//action for downloading a file
public ActionResult Download(string FileID)
{
int CurrentFileID = Convert.ToInt32(FileID);
var filesCol = obj.GetFiles();
string fullFilePath = (from fls in filesCol
where fls.FileId == CurrentFileID
select fls.FilePath).First();
string contentType = MimeMapping.GetMimeMapping(fullFilePath);
return File(fullFilePath, contentType, new FileInfo(fullFilePath).Name);
}
UPDATE2:
public ActionResult ViewOnline(string FileID)
{
int CurrentFileID = Convert.ToInt32(FileID);
var filesCol = obj.GetFiles();
string fullFilePath = (from fls in filesCol
where fls.FileId == CurrentFileID
select fls.FilePath).First();
string text = System.IO.File.ReadAllText(fullFilePath);
return Content(text);
}
I am creating a Excel Addin through which i want to access a database. code is as follows
[ExcelFunction("My First Excel-DNA Function")]
public static string GreetFunction(string name)
{
GetConnection();
return "Hello" + " " + name;
}
public static void GetConnection()
{
//db = new SQLiteConnection("Data Source="+System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\Database\\XLSQLiteDemo.sqlite");
db = new SQLiteConnection("Data Source=Database/XLSQLiteDemo.sqlite");
try
{
db.Open();
cmd = db.CreateCommand();
System.Windows.MessageBox.Show("Connection created");
}
catch (SQLiteException ex)
{
System.Windows.MessageBox.Show(ex.ToString());
}
}
so when i give absolute path like c:/test/firstlibrary.../XLSQLiteDemo.sqlite it works.
but when i use relative path like db = new SQLiteConnection("Data Source=Database/XLSQLiteDemo.sqlite");
it throws an exception: unable to open database file error code 14.
the code which is in comment i.e.
//db = new SQLiteConnection("Data Source="+System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\Database\\XLSQLiteDemo.sqlite");
also doesn't work i.e. it calculates the absolute path but when i tried to debug; debugging is automatically terminated after db.Open();
and output in excel sheet is also #Value which indicates some error.
#adrino may be the "file" word in your string is the problem.remove it.
string relativePath = #"Database\XLSQLiteDemo.sqlite";
string currentPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string absolutePath = System.IO.Path.Combine(currentPath, relativePath);
absolutePath=absolutePath.Remove(0, 6);//this code is written to remove file word from absolute path
string connectionString = string.Format("Data Source={0}", absolutePath);
this works on my machine.tell me if its correct.