PDFファイルを読み込んで、それに関する情報を表示するプログラムを作成しました。それはうまく動作します。スコープ外の変数はどのように使用しますか? (エラー:CS0136)
class Program
{
static void Main(string[] args)
{
//some variables
string plabels = null;
string text2Search = "IX";
PdfReader reader = new PdfReader("file.pdf");
string[] labels = PdfPageLabels.GetPageLabels(reader);
for (int l = 0; l < labels.Length; l++)
{
plabels += labels[l] + "\n";
}
Console.WriteLine(plabels.IndexOf(text2Search, StringComparison.CurrentCultureIgnoreCase));
Console.ReadLine();
}
}
また、PDFファイルを読み込んでコピーを作成する別のプログラムも作成しました。それは正常に動作します。
class Program
{
static void Main(string[] args)
{
byte[] bytes;
using (var ms = new MemoryStream())
{
using (var reader = new PdfReader("file.pdf"))
{
using (var stamper = new PdfStamper(reader, ms))
{
}
}
//grab the bytes before closing things out
bytes = ms.ToArray();
}
File.WriteAllBytes("output.pdf", bytes);
}
}
これらの2つのプログラムを1つにまとめることはできません。あなたのコメントへ
EDIT
おかげで私は、エラーを発見。今すぐコードがコンパイルされますが、実行すると"Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object."
エラーポイントはfor(int l = 0; l < labels.Length; l++)
になります。
class Program
{
static void Main(string[] args)
{
byte[] bytes;
using (var ms = new MemoryStream())
{
using (var reader = new PdfReader("file.pdf"))
{
//some variables
string plabels = null;
string text2Search = "IX";
string[] labels = PdfPageLabels.GetPageLabels(reader);
for(int l = 0; l < labels.Length; l++)
{
plabels += labels[l] + "\n";
}
Console.WriteLine(plabels.IndexOf(text2Search, StringComparison.CurrentCultureIgnoreCase));
Console.ReadLine();
using (var stamper = new PdfStamper(reader, ms))
{
}
}
//grab the bytes before closing things out
bytes = ms.ToArray();
}
File.WriteAllBytes("output.pdf", bytes);
}
}
現在のスコープの外に変数を使用することはできません。スコープの全体の点です。あなたができることは、より高いスコープで変数を定義して、より多くの場所でスコープ内にあるようにすることです。 –
@BradleyUffnerコードを変更しました。今はうまくコンパイルされますが、実行時にエラーが発生します。詳細は、私の更新情報の投稿をご覧ください。 – menteith
それから、 'PdfPageLabels.GetPageLabels()'は 'null'を返さなければならないので、' labels.Length'への参照は例外をスローします。最初に 'null'をチェックするか、なぜ' GetPageLabels() 'が' null'を返すのかを理解して修正してください。 –