アプリ版:「スタンプのみでお礼する」機能のリリースについて

【C#】テキストボックスに入っているファイル名(文字列)のオープン

C#初心者です。

C#で、テキストボックスに入力されているファイルをオープンして、一行ずつ読み込みたいのですが、なかなかうまくいきません。

分かる方いらっしゃいましたら教えていただけると幸いです。
宜しくお願いいたします。

A 回答 (1件)

>C言語→C#に変換


の返信はないわけ?
お礼もまともにできないのにこの先やっていけるのかと。


面倒なので、

-ainput.txt -bkeyword

という引数から input.txt から keyword を検索するC言語のコード

#include <string.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
FILE* fp;
FILE* fpp;
int i;
char KEYWORD[256];
char buf[256];

//(1)アウトプットファイルのオープン
fpp = fopen("output.txt", "w");
if (fpp == NULL)
{
printf("open error!\n");
return 1;
}
for (i = 1; i < argc; ++i)
{
//(2)入力ファイルのオープン
if (strncmp(argv[i], "-a", 2) == 0)
{
fp = fopen(argv[i] + 2, "r");
if (fp == NULL)
{
printf("open error!\n");
fclose(fpp);
return 1;
}
}
//(3)キーワードの代入
else if (strncmp(argv[i], "-b", 2) == 0) {
strcpy(KEYWORD, argv[i] + 2);
}
}
//(4)一行読み込む
while (fgets(buf, sizeof(buf), fp) != NULL)
{
//(5)キーワードの条件で文字列抽出
if (strstr(buf, KEYWORD) != NULL)
{
//(6)アウトプットファイルに出力
fprintf(fpp, "%s", buf);
}
}
//ファイルクローズ
fclose(fp);
fclose(fpp);
return 0;
}


そのC#版

using System;
using System.IO;
using System.Text;

public class Program1
{
static int Main(string[] args)
{
string inpath = null;
string keyword = null;
string outpath = "output.txt";

foreach (string cmd in args) {
if (cmd.IndexOf("-a") == 0) {
inpath = cmd.Substring(2);
}
else if (cmd.IndexOf("-b") == 0) {
keyword = cmd.Substring(2);
}
}
if (inpath == null || keyword == null) {
return 1;
}

StreamReader sr = null;
StreamWriter sw = null;
try {
sr = new StreamReader(inpath, Encoding.GetEncoding(932));
sw = new StreamWriter(outpath, false, Encoding.GetEncoding(932));

string line;
while ((line = sr.ReadLine()) != null) {
if (line.IndexOf(keyword) != -1) {
sw.WriteLine(line);
}
}
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
finally {
if (sr != null) {
sr.Close();
}
if (sw != null) {
sw.Close();
}
}
return 0;
}
}

あとは自分で考えて。
    • good
    • 0
この回答へのお礼

すみません、仕事で納期が迫っていまして、いっぱいいっぱいになっていました。

ありがとうございます。
非常に参考になりました。

お礼日時:2010/08/04 16:43

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!