从VBA通过shell执行的C#不会创建文件 [英] C# executed via shell from VBA doesnt create file
问题描述
Backstory:我从一个程序中获得了一大堆sql代码,我想用它来转储excel中的数据。从VBA执行此代码会产生大量错误,并且代码块很大并且要经过混乱。
在C#中运行查询工作正常所以我'我写了一个程序,它抓取数据和转储文件我称之为excelDump.csv
为了便于使用,为了避免单独运行这个程序我打电话该程序通过vba宏。一旦程序执行完毕,我就抓住(在vba中)dumb中的数据并填充我的excel表。
c#程序被调用,控制台显示我想要的一切,它以正确的退出代码关闭,我在尝试打开转储之前在VBA中确认此代码。
这是我在C#中运行的代码
Backstory: I got a huge wall of sql code from a program which I want to use to dump data in excel. Executing this code from VBA produces a lot of errors and the chunk of code is to big and jumbled to go through.
Running the query in C# works fine so I've written a program which grabs the data and dumps in a file I call excelDump.csv
For ease of use in order to avoid having to run this program separately I call the program via vba macro. Once the program has executed I grab (in vba) the data in the dumb and populate my excel sheet.
The c# program gets called, the console shows everything I want, it closes with the correct exit code and I confirm this code in VBA before trying to open the dump.
Here is the code that I run in C#
public void DumpToExcel()
{
using (System.IO.StreamWriter fs = new System.IO.StreamWriter("excelDump.csv"))
{
// Loop through the fields and add headers
for (int i = 0; i < myReader.FieldCount; i++)
{
string name = myReader.GetName(i);
if (name.Contains(","))
name = "\"" + name + "\"";
fs.Write(name + ",");
}
fs.WriteLine();
// Loop through the rows and output the data
while (myReader.Read())
{
for (int i = 0; i < myReader.FieldCount; i++)
{
string value = myReader[i].ToString();
if (value.Contains(","))
value = "\"" + value + "\"";
fs.Write(value + ",");
}
fs.WriteLine();
}
fs.Close();
}
}
我尝试了什么:
起初我认为问题是程序无法覆盖文件所以我尝试删除文件但没有去。当我从visual studio运行它或从exe发布版本时,该程序工作正常。但是从shell调用它不会创建一个新文件。使用file.delete就可以删除旧的了。
我想也许c#程序在创建文件之前很快完成但是我在导入数据之前等待了没有。
What I have tried:
At first I thought the problem was that the program was unable to overwrite the file so I tried deleting the file but no go. The program works fine when I run it from visual studio or the release build from exe. But calling it from shell doesnt create a new file. Using file.delete can delete the old one just fine.
I thought maybe the c# program finishes to quickly before the files is created but Ive waited before importing data and still nothing.
推荐答案
如果字段本身包含一个或多个双引号,您还需要使用双引号封装字段。
You also need to encapsulate a field with double quotes if the field itself contains one or more double quotes.
执行宏的工作目录可能与文件的文件夹不同。使用完整路径,如c:\\temp \\excelDump.csv
,您处于更安全的一面。
The working directory for execution of the macro may differ from the folder of the file. With a full path like "c:\\temp\\excelDump.csv"
, you are on the safer side.
这篇关于从VBA通过shell执行的C#不会创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!