SftpTests.cs 225 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338
  1. using System.Diagnostics;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.IntegrationTests.Common;
  4. using Renci.SshNet.Sftp;
  5. namespace Renci.SshNet.IntegrationTests
  6. {
  7. // TODO: DeleteDirectory (fail + success
  8. // TODO: DeleteFile (fail + success
  9. // TODO: Delete (fail + success
  10. [TestClass]
  11. public class SftpTests : TestBase
  12. {
  13. private IConnectionInfoFactory _connectionInfoFactory;
  14. private IConnectionInfoFactory _adminConnectionInfoFactory;
  15. private IRemotePathTransformation _remotePathTransformation;
  16. [TestInitialize]
  17. public void SetUp()
  18. {
  19. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  20. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  21. _remotePathTransformation = RemotePathTransformation.ShellQuote;
  22. }
  23. [DataTestMethod]
  24. [DynamicData(nameof(GetSftpUploadFileFileStreamData), DynamicDataSourceType.Method)]
  25. public void Sftp_UploadFile_FileStream(int size)
  26. {
  27. var file = CreateTempFile(size);
  28. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  29. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  30. {
  31. client.Connect();
  32. var remoteFile = GenerateUniqueRemoteFileName();
  33. if (client.Exists(remoteFile))
  34. {
  35. client.Delete(remoteFile);
  36. }
  37. try
  38. {
  39. client.UploadFile(fs, remoteFile);
  40. using (var memoryStream = new MemoryStream(size))
  41. {
  42. client.DownloadFile(remoteFile, memoryStream);
  43. memoryStream.Position = 0;
  44. Assert.AreEqual(CreateFileHash(file), CreateHash(memoryStream));
  45. }
  46. }
  47. finally
  48. {
  49. if (client.Exists(remoteFile))
  50. {
  51. client.Delete(remoteFile);
  52. }
  53. }
  54. }
  55. }
  56. [TestMethod]
  57. public void Sftp_ConnectDisconnect_Serial()
  58. {
  59. const int iterations = 100;
  60. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  61. {
  62. for (var i = 1; i <= iterations; i++)
  63. {
  64. client.Connect();
  65. client.Disconnect();
  66. }
  67. }
  68. }
  69. [TestMethod]
  70. public void Sftp_ConnectDisconnect_Parallel()
  71. {
  72. const int iterations = 10;
  73. const int threads = 20;
  74. var startEvent = new ManualResetEvent(false);
  75. var tasks = Enumerable.Range(1, threads).Select(i =>
  76. {
  77. return Task.Factory.StartNew(() =>
  78. {
  79. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  80. {
  81. startEvent.WaitOne();
  82. for (var j = 0; j < iterations; j++)
  83. {
  84. client.Connect();
  85. client.Disconnect();
  86. }
  87. }
  88. });
  89. }).ToArray();
  90. startEvent.Set();
  91. Task.WaitAll(tasks);
  92. }
  93. [TestMethod]
  94. public void Sftp_BeginUploadFile()
  95. {
  96. const string content = "SftpBeginUploadFile";
  97. var expectedByteCount = (ulong) Encoding.ASCII.GetByteCount(content);
  98. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  99. {
  100. client.Connect();
  101. var remoteFile = GenerateUniqueRemoteFileName();
  102. if (client.Exists(remoteFile))
  103. {
  104. client.Delete(remoteFile);
  105. }
  106. try
  107. {
  108. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(content)))
  109. {
  110. IAsyncResult asyncResultCallback = null;
  111. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, ar => asyncResultCallback = ar);
  112. Assert.IsTrue(asyncResult.AsyncWaitHandle.WaitOne(10000));
  113. // check async result
  114. var sftpUploadAsyncResult = asyncResult as SftpUploadAsyncResult;
  115. Assert.IsNotNull(sftpUploadAsyncResult);
  116. Assert.IsFalse(sftpUploadAsyncResult.IsUploadCanceled);
  117. Assert.IsTrue(sftpUploadAsyncResult.IsCompleted);
  118. Assert.IsFalse(sftpUploadAsyncResult.CompletedSynchronously);
  119. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResult.UploadedBytes);
  120. // check async result callback
  121. var sftpUploadAsyncResultCallback = asyncResultCallback as SftpUploadAsyncResult;
  122. Assert.IsNotNull(sftpUploadAsyncResultCallback);
  123. Assert.IsFalse(sftpUploadAsyncResultCallback.IsUploadCanceled);
  124. Assert.IsTrue(sftpUploadAsyncResultCallback.IsCompleted);
  125. Assert.IsFalse(sftpUploadAsyncResultCallback.CompletedSynchronously);
  126. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResultCallback.UploadedBytes);
  127. }
  128. // check uploaded file
  129. using (var memoryStream = new MemoryStream())
  130. {
  131. client.DownloadFile(remoteFile, memoryStream);
  132. memoryStream.Position = 0;
  133. var remoteContent = Encoding.ASCII.GetString(memoryStream.ToArray());
  134. Assert.AreEqual(content, remoteContent);
  135. }
  136. }
  137. finally
  138. {
  139. if (client.Exists(remoteFile))
  140. {
  141. client.Delete(remoteFile);
  142. }
  143. }
  144. }
  145. }
  146. [TestMethod]
  147. public void Sftp_Create_ExistingFile()
  148. {
  149. var encoding = Encoding.UTF8;
  150. var initialContent = "Gert & Ann & Lisa";
  151. var newContent1 = "Sofie";
  152. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  153. var newContent2 = "Lisa & Sofie";
  154. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  155. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  156. {
  157. client.Connect();
  158. var remoteFile = GenerateUniqueRemoteFileName();
  159. if (client.Exists(remoteFile))
  160. {
  161. client.DeleteFile(remoteFile);
  162. }
  163. try
  164. {
  165. client.WriteAllText(remoteFile, initialContent);
  166. #region Write less bytes than the current content, overwriting part of that content
  167. using (var fs = client.Create(remoteFile))
  168. using (var sw = new StreamWriter(fs, encoding))
  169. {
  170. sw.Write(newContent1);
  171. }
  172. var actualContent1 = client.ReadAllBytes(remoteFile);
  173. Assert.IsTrue(newContent1Bytes.IsEqualTo(actualContent1));
  174. #endregion Write less bytes than the current content, overwriting part of that content
  175. #region Write more bytes than the current content, overwriting and appending to that content
  176. using (var fs = client.Create(remoteFile))
  177. using (var sw = new StreamWriter(fs, encoding))
  178. {
  179. sw.Write(newContent2);
  180. }
  181. var actualContent2 = client.ReadAllBytes(remoteFile);
  182. Assert.IsTrue(newContent2Bytes.IsEqualTo(actualContent2));
  183. #endregion Write more bytes than the current content, overwriting and appending to that content
  184. }
  185. finally
  186. {
  187. if (client.Exists(remoteFile))
  188. {
  189. client.DeleteFile(remoteFile);
  190. }
  191. }
  192. }
  193. }
  194. [TestMethod]
  195. public void Sftp_Create_DirectoryDoesNotExist()
  196. {
  197. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  198. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  199. {
  200. client.Connect();
  201. if (client.Exists(remoteFile))
  202. {
  203. client.DeleteFile(remoteFile);
  204. }
  205. SftpFileStream fs = null;
  206. try
  207. {
  208. fs = client.Create(remoteFile);
  209. Assert.Fail();
  210. }
  211. catch (SftpPathNotFoundException ex)
  212. {
  213. Assert.IsNull(ex.InnerException);
  214. Assert.AreEqual("No such file", ex.Message);
  215. }
  216. finally
  217. {
  218. fs?.Dispose();
  219. if (client.Exists(remoteFile))
  220. {
  221. client.DeleteFile(remoteFile);
  222. }
  223. }
  224. }
  225. }
  226. [TestMethod]
  227. public void Sftp_Create_FileDoesNotExist()
  228. {
  229. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  230. {
  231. client.BufferSize = 512 * 1024;
  232. client.Connect();
  233. var remoteFile = GenerateUniqueRemoteFileName();
  234. if (client.Exists(remoteFile))
  235. {
  236. client.DeleteFile(remoteFile);
  237. }
  238. try
  239. {
  240. using (var imageStream = GetData("resources.issue #70.png"))
  241. {
  242. using (var fs = client.Create(remoteFile))
  243. {
  244. byte[] buffer = new byte[Math.Min(client.BufferSize, imageStream.Length)];
  245. int bytesRead;
  246. while ((bytesRead = imageStream.Read(buffer, offset: 0, buffer.Length)) > 0)
  247. {
  248. fs.Write(buffer, offset: 0, bytesRead);
  249. }
  250. }
  251. using (var memoryStream = new MemoryStream())
  252. {
  253. client.DownloadFile(remoteFile, memoryStream);
  254. memoryStream.Position = 0;
  255. imageStream.Position = 0;
  256. Assert.AreEqual(CreateHash(imageStream), CreateHash(memoryStream));
  257. }
  258. }
  259. }
  260. finally
  261. {
  262. if (client.Exists(remoteFile))
  263. {
  264. client.DeleteFile(remoteFile);
  265. }
  266. }
  267. }
  268. }
  269. [TestMethod]
  270. public void Sftp_AppendAllLines_NoEncoding_ExistingFile()
  271. {
  272. var initialContent = "\u0100ert & Ann";
  273. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  274. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  275. Environment.NewLine;
  276. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  277. {
  278. client.Connect();
  279. var remoteFile = GenerateUniqueRemoteFileName();
  280. if (client.Exists(remoteFile))
  281. {
  282. client.DeleteFile(remoteFile);
  283. }
  284. try
  285. {
  286. client.WriteAllText(remoteFile, initialContent);
  287. client.AppendAllLines(remoteFile, linesToAppend);
  288. var text = client.ReadAllText(remoteFile);
  289. Assert.AreEqual(expectedContent, text);
  290. // ensure we didn't write an UTF-8 BOM
  291. using (var fs = client.OpenRead(remoteFile))
  292. {
  293. var firstByte = fs.ReadByte();
  294. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  295. }
  296. }
  297. finally
  298. {
  299. if (client.Exists(remoteFile))
  300. {
  301. client.DeleteFile(remoteFile);
  302. }
  303. }
  304. }
  305. }
  306. [TestMethod]
  307. public void Sftp_AppendAllLines_NoEncoding_DirectoryDoesNotExist()
  308. {
  309. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  310. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  311. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  312. {
  313. client.Connect();
  314. if (client.Exists(remoteFile))
  315. {
  316. client.DeleteFile(remoteFile);
  317. }
  318. try
  319. {
  320. client.AppendAllLines(remoteFile, linesToAppend);
  321. Assert.Fail();
  322. }
  323. catch (SftpPathNotFoundException ex)
  324. {
  325. Assert.IsNull(ex.InnerException);
  326. Assert.AreEqual("No such file", ex.Message);
  327. }
  328. finally
  329. {
  330. if (client.Exists(remoteFile))
  331. {
  332. client.DeleteFile(remoteFile);
  333. }
  334. }
  335. }
  336. }
  337. [TestMethod]
  338. public void Sftp_AppendAllLines_NoEncoding_FileDoesNotExist()
  339. {
  340. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  341. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  342. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  343. {
  344. client.Connect();
  345. var remoteFile = GenerateUniqueRemoteFileName();
  346. if (client.Exists(remoteFile))
  347. {
  348. client.DeleteFile(remoteFile);
  349. }
  350. try
  351. {
  352. client.AppendAllLines(remoteFile, linesToAppend);
  353. var text = client.ReadAllText(remoteFile);
  354. Assert.AreEqual(expectedContent, text);
  355. // ensure we didn't write an UTF-8 BOM
  356. using (var fs = client.OpenRead(remoteFile))
  357. {
  358. var firstByte = fs.ReadByte();
  359. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  360. }
  361. }
  362. finally
  363. {
  364. if (client.Exists(remoteFile))
  365. {
  366. client.DeleteFile(remoteFile);
  367. }
  368. }
  369. }
  370. }
  371. [TestMethod]
  372. public void Sftp_AppendAllText_NoEncoding_ExistingFile()
  373. {
  374. var initialContent = "\u0100ert & Ann";
  375. var contentToAppend = "Forever&\u0116ver";
  376. var expectedContent = initialContent + contentToAppend;
  377. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  378. {
  379. client.Connect();
  380. var remoteFile = GenerateUniqueRemoteFileName();
  381. if (client.Exists(remoteFile))
  382. {
  383. client.DeleteFile(remoteFile);
  384. }
  385. try
  386. {
  387. client.WriteAllText(remoteFile, initialContent);
  388. client.AppendAllText(remoteFile, contentToAppend);
  389. var text = client.ReadAllText(remoteFile);
  390. Assert.AreEqual(expectedContent, text);
  391. // ensure we didn't write an UTF-8 BOM
  392. using (var fs = client.OpenRead(remoteFile))
  393. {
  394. var firstByte = fs.ReadByte();
  395. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  396. }
  397. }
  398. finally
  399. {
  400. if (client.Exists(remoteFile))
  401. {
  402. client.DeleteFile(remoteFile);
  403. }
  404. }
  405. }
  406. }
  407. [TestMethod]
  408. public void Sftp_AppendAllText_NoEncoding_DirectoryDoesNotExist()
  409. {
  410. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  411. var contentToAppend = "Forever&\u0116ver";
  412. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  413. {
  414. client.Connect();
  415. if (client.Exists(remoteFile))
  416. {
  417. client.DeleteFile(remoteFile);
  418. }
  419. try
  420. {
  421. client.AppendAllText(remoteFile, contentToAppend);
  422. Assert.Fail();
  423. }
  424. catch (SftpPathNotFoundException ex)
  425. {
  426. Assert.IsNull(ex.InnerException);
  427. Assert.AreEqual("No such file", ex.Message);
  428. }
  429. finally
  430. {
  431. if (client.Exists(remoteFile))
  432. {
  433. client.DeleteFile(remoteFile);
  434. }
  435. }
  436. }
  437. }
  438. [TestMethod]
  439. public void Sftp_AppendAllText_NoEncoding_FileDoesNotExist()
  440. {
  441. var contentToAppend = "Forever&\u0116ver";
  442. var expectedContent = contentToAppend;
  443. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  444. {
  445. client.Connect();
  446. var remoteFile = GenerateUniqueRemoteFileName();
  447. if (client.Exists(remoteFile))
  448. {
  449. client.DeleteFile(remoteFile);
  450. }
  451. try
  452. {
  453. client.AppendAllText(remoteFile, contentToAppend);
  454. var text = client.ReadAllText(remoteFile);
  455. Assert.AreEqual(expectedContent, text);
  456. // ensure we didn't write an UTF-8 BOM
  457. using (var fs = client.OpenRead(remoteFile))
  458. {
  459. var firstByte = fs.ReadByte();
  460. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  461. }
  462. }
  463. finally
  464. {
  465. if (client.Exists(remoteFile))
  466. {
  467. client.DeleteFile(remoteFile);
  468. }
  469. }
  470. }
  471. }
  472. [TestMethod]
  473. public void Sftp_AppendText_NoEncoding_ExistingFile()
  474. {
  475. var initialContent = "\u0100ert & Ann";
  476. var contentToAppend = "Forever&\u0116ver";
  477. var expectedContent = initialContent + contentToAppend;
  478. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  479. {
  480. client.Connect();
  481. var remoteFile = GenerateUniqueRemoteFileName();
  482. if (client.Exists(remoteFile))
  483. {
  484. client.DeleteFile(remoteFile);
  485. }
  486. try
  487. {
  488. client.WriteAllText(remoteFile, initialContent);
  489. using (var sw = client.AppendText(remoteFile))
  490. {
  491. sw.Write(contentToAppend);
  492. }
  493. var text = client.ReadAllText(remoteFile);
  494. Assert.AreEqual(expectedContent, text);
  495. // ensure we didn't write an UTF-8 BOM
  496. using (var fs = client.OpenRead(remoteFile))
  497. {
  498. var firstByte = fs.ReadByte();
  499. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  500. }
  501. }
  502. finally
  503. {
  504. if (client.Exists(remoteFile))
  505. {
  506. client.DeleteFile(remoteFile);
  507. }
  508. }
  509. }
  510. }
  511. [TestMethod]
  512. public void Sftp_AppendText_NoEncoding_DirectoryDoesNotExist()
  513. {
  514. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  515. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  516. {
  517. client.Connect();
  518. if (client.Exists(remoteFile))
  519. {
  520. client.DeleteFile(remoteFile);
  521. }
  522. StreamWriter sw = null;
  523. try
  524. {
  525. sw = client.AppendText(remoteFile);
  526. Assert.Fail();
  527. }
  528. catch (SftpPathNotFoundException ex)
  529. {
  530. Assert.IsNull(ex.InnerException);
  531. Assert.AreEqual("No such file", ex.Message);
  532. }
  533. finally
  534. {
  535. sw?.Dispose();
  536. if (client.Exists(remoteFile))
  537. {
  538. client.DeleteFile(remoteFile);
  539. }
  540. }
  541. }
  542. }
  543. [TestMethod]
  544. public void Sftp_AppendText_NoEncoding_FileDoesNotExist()
  545. {
  546. var contentToAppend = "\u0100ert & Ann";
  547. var expectedContent = contentToAppend;
  548. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  549. {
  550. client.Connect();
  551. var remoteFile = GenerateUniqueRemoteFileName();
  552. if (client.Exists(remoteFile))
  553. {
  554. client.DeleteFile(remoteFile);
  555. }
  556. try
  557. {
  558. using (var sw = client.AppendText(remoteFile))
  559. {
  560. sw.Write(contentToAppend);
  561. }
  562. // ensure we didn't write an UTF-8 BOM
  563. using (var fs = client.OpenRead(remoteFile))
  564. {
  565. var firstByte = fs.ReadByte();
  566. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  567. }
  568. }
  569. finally
  570. {
  571. if (client.Exists(remoteFile))
  572. {
  573. client.DeleteFile(remoteFile);
  574. }
  575. }
  576. }
  577. }
  578. [TestMethod]
  579. public void Sftp_AppendAllLines_Encoding_ExistingFile()
  580. {
  581. var initialContent = "\u0100ert & Ann";
  582. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  583. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  584. Environment.NewLine;
  585. var encoding = GetRandomEncoding();
  586. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  587. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  588. {
  589. client.Connect();
  590. var remoteFile = GenerateUniqueRemoteFileName();
  591. if (client.Exists(remoteFile))
  592. {
  593. client.DeleteFile(remoteFile);
  594. }
  595. try
  596. {
  597. client.WriteAllText(remoteFile, initialContent, encoding);
  598. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  599. var text = client.ReadAllText(remoteFile, encoding);
  600. Assert.AreEqual(expectedContent, text);
  601. using (var fs = client.OpenRead(remoteFile))
  602. {
  603. var actualBytes = new byte[fs.Length];
  604. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  605. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  606. }
  607. }
  608. finally
  609. {
  610. if (client.Exists(remoteFile))
  611. {
  612. client.DeleteFile(remoteFile);
  613. }
  614. }
  615. }
  616. }
  617. [TestMethod]
  618. public void Sftp_AppendAllLines_Encoding_DirectoryDoesNotExist()
  619. {
  620. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  621. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  622. var encoding = GetRandomEncoding();
  623. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  624. {
  625. client.Connect();
  626. if (client.Exists(remoteFile))
  627. {
  628. client.DeleteFile(remoteFile);
  629. }
  630. try
  631. {
  632. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  633. Assert.Fail();
  634. }
  635. catch (SftpPathNotFoundException ex)
  636. {
  637. Assert.IsNull(ex.InnerException);
  638. Assert.AreEqual("No such file", ex.Message);
  639. }
  640. finally
  641. {
  642. if (client.Exists(remoteFile))
  643. {
  644. client.DeleteFile(remoteFile);
  645. }
  646. }
  647. }
  648. }
  649. [TestMethod]
  650. public void Sftp_AppendAllLines_Encoding_FileDoesNotExist()
  651. {
  652. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  653. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  654. var encoding = GetRandomEncoding();
  655. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  656. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  657. {
  658. client.Connect();
  659. var remoteFile = GenerateUniqueRemoteFileName();
  660. if (client.Exists(remoteFile))
  661. {
  662. client.DeleteFile(remoteFile);
  663. }
  664. try
  665. {
  666. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  667. var text = client.ReadAllText(remoteFile, encoding);
  668. Assert.AreEqual(expectedContent, text);
  669. using (var fs = client.OpenRead(remoteFile))
  670. {
  671. var actualBytes = new byte[fs.Length];
  672. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  673. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  674. }
  675. }
  676. finally
  677. {
  678. if (client.Exists(remoteFile))
  679. {
  680. client.DeleteFile(remoteFile);
  681. }
  682. }
  683. }
  684. }
  685. [TestMethod]
  686. public void Sftp_AppendAllText_Encoding_ExistingFile()
  687. {
  688. var initialContent = "\u0100ert & Ann";
  689. var contentToAppend = "Forever&\u0116ver";
  690. var expectedContent = initialContent + contentToAppend;
  691. var encoding = GetRandomEncoding();
  692. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  693. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  694. {
  695. client.Connect();
  696. var remoteFile = GenerateUniqueRemoteFileName();
  697. if (client.Exists(remoteFile))
  698. {
  699. client.DeleteFile(remoteFile);
  700. }
  701. try
  702. {
  703. client.WriteAllText(remoteFile, initialContent, encoding);
  704. client.AppendAllText(remoteFile, contentToAppend, encoding);
  705. var text = client.ReadAllText(remoteFile, encoding);
  706. Assert.AreEqual(expectedContent, text);
  707. using (var fs = client.OpenRead(remoteFile))
  708. {
  709. var actualBytes = new byte[fs.Length];
  710. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  711. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  712. }
  713. }
  714. finally
  715. {
  716. if (client.Exists(remoteFile))
  717. {
  718. client.DeleteFile(remoteFile);
  719. }
  720. }
  721. }
  722. }
  723. [TestMethod]
  724. public void Sftp_AppendAllText_Encoding_DirectoryDoesNotExist()
  725. {
  726. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  727. const string contentToAppend = "Forever&\u0116ver";
  728. var encoding = GetRandomEncoding();
  729. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  730. {
  731. client.Connect();
  732. if (client.Exists(remoteFile))
  733. {
  734. client.DeleteFile(remoteFile);
  735. }
  736. try
  737. {
  738. client.AppendAllText(remoteFile, contentToAppend, encoding);
  739. Assert.Fail();
  740. }
  741. catch (SftpPathNotFoundException ex)
  742. {
  743. Assert.IsNull(ex.InnerException);
  744. Assert.AreEqual("No such file", ex.Message);
  745. }
  746. finally
  747. {
  748. if (client.Exists(remoteFile))
  749. {
  750. client.DeleteFile(remoteFile);
  751. }
  752. }
  753. }
  754. }
  755. [TestMethod]
  756. public void Sftp_AppendAllText_Encoding_FileDoesNotExist()
  757. {
  758. const string contentToAppend = "Forever&\u0116ver";
  759. var expectedContent = contentToAppend;
  760. var encoding = GetRandomEncoding();
  761. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  762. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  763. {
  764. client.Connect();
  765. var remoteFile = GenerateUniqueRemoteFileName();
  766. if (client.Exists(remoteFile))
  767. {
  768. client.DeleteFile(remoteFile);
  769. }
  770. try
  771. {
  772. client.AppendAllText(remoteFile, contentToAppend, encoding);
  773. var text = client.ReadAllText(remoteFile, encoding);
  774. Assert.AreEqual(expectedContent, text);
  775. using (var fs = client.OpenRead(remoteFile))
  776. {
  777. var actualBytes = new byte[fs.Length];
  778. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  779. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  780. }
  781. }
  782. finally
  783. {
  784. if (client.Exists(remoteFile))
  785. {
  786. client.DeleteFile(remoteFile);
  787. }
  788. }
  789. }
  790. }
  791. [TestMethod]
  792. public void Sftp_AppendText_Encoding_ExistingFile()
  793. {
  794. const string initialContent = "\u0100ert & Ann";
  795. const string contentToAppend = "Forever&\u0116ver";
  796. var expectedContent = initialContent + contentToAppend;
  797. var encoding = GetRandomEncoding();
  798. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  799. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  800. {
  801. client.Connect();
  802. var remoteFile = GenerateUniqueRemoteFileName();
  803. if (client.Exists(remoteFile))
  804. {
  805. client.DeleteFile(remoteFile);
  806. }
  807. try
  808. {
  809. client.WriteAllText(remoteFile, initialContent, encoding);
  810. using (var sw = client.AppendText(remoteFile, encoding))
  811. {
  812. sw.Write(contentToAppend);
  813. }
  814. var text = client.ReadAllText(remoteFile, encoding);
  815. Assert.AreEqual(expectedContent, text);
  816. using (var fs = client.OpenRead(remoteFile))
  817. {
  818. var actualBytes = new byte[fs.Length];
  819. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  820. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  821. }
  822. }
  823. finally
  824. {
  825. if (client.Exists(remoteFile))
  826. {
  827. client.DeleteFile(remoteFile);
  828. }
  829. }
  830. }
  831. }
  832. [TestMethod]
  833. public void Sftp_AppendText_Encoding_DirectoryDoesNotExist()
  834. {
  835. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  836. var encoding = GetRandomEncoding();
  837. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  838. {
  839. client.Connect();
  840. if (client.Exists(remoteFile))
  841. {
  842. client.DeleteFile(remoteFile);
  843. }
  844. StreamWriter sw = null;
  845. try
  846. {
  847. sw = client.AppendText(remoteFile, encoding);
  848. Assert.Fail();
  849. }
  850. catch (SftpPathNotFoundException ex)
  851. {
  852. Assert.IsNull(ex.InnerException);
  853. Assert.AreEqual("No such file", ex.Message);
  854. }
  855. finally
  856. {
  857. sw?.Dispose();
  858. if (client.Exists(remoteFile))
  859. {
  860. client.DeleteFile(remoteFile);
  861. }
  862. }
  863. }
  864. }
  865. [TestMethod]
  866. public void Sftp_AppendText_Encoding_FileDoesNotExist()
  867. {
  868. var encoding = GetRandomEncoding();
  869. const string contentToAppend = "\u0100ert & Ann";
  870. var expectedBytes = GetBytesWithPreamble(contentToAppend, encoding);
  871. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  872. {
  873. client.Connect();
  874. var remoteFile = GenerateUniqueRemoteFileName();
  875. if (client.Exists(remoteFile))
  876. {
  877. client.DeleteFile(remoteFile);
  878. }
  879. try
  880. {
  881. using (var sw = client.AppendText(remoteFile, encoding))
  882. {
  883. sw.Write(contentToAppend);
  884. }
  885. using (var fs = client.OpenRead(remoteFile))
  886. {
  887. var actualBytes = new byte[fs.Length];
  888. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  889. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  890. }
  891. }
  892. finally
  893. {
  894. if (client.Exists(remoteFile))
  895. {
  896. client.DeleteFile(remoteFile);
  897. }
  898. }
  899. }
  900. }
  901. [TestMethod]
  902. public void Sftp_CreateText_NoEncoding_ExistingFile()
  903. {
  904. var encoding = new UTF8Encoding(false, true);
  905. const string initialContent = "\u0100ert & Ann";
  906. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  907. const string newContent = "\u0116ver";
  908. const string expectedContent = "\u0116ver" + " & Ann";
  909. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  910. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  911. {
  912. client.Connect();
  913. var remoteFile = GenerateUniqueRemoteFileName();
  914. if (client.Exists(remoteFile))
  915. {
  916. client.DeleteFile(remoteFile);
  917. }
  918. try
  919. {
  920. client.WriteAllText(remoteFile, initialContent);
  921. using (client.CreateText(remoteFile))
  922. {
  923. }
  924. // verify that original content is left untouched
  925. using (var fs = client.OpenRead(remoteFile))
  926. {
  927. var actualBytes = new byte[fs.Length];
  928. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  929. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  930. }
  931. // write content that is less bytes than original content
  932. using (var sw = client.CreateText(remoteFile))
  933. {
  934. sw.Write(newContent);
  935. }
  936. // verify that original content is only partially overwritten
  937. var text = client.ReadAllText(remoteFile);
  938. Assert.AreEqual(expectedContent, text);
  939. using (var fs = client.OpenRead(remoteFile))
  940. {
  941. var actualBytes = new byte[fs.Length];
  942. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  943. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  944. }
  945. }
  946. finally
  947. {
  948. if (client.Exists(remoteFile))
  949. {
  950. client.DeleteFile(remoteFile);
  951. }
  952. }
  953. }
  954. }
  955. [TestMethod]
  956. public void Sftp_CreateText_NoEncoding_DirectoryDoesNotExist()
  957. {
  958. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  959. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  960. {
  961. client.Connect();
  962. if (client.Exists(remoteFile))
  963. {
  964. client.DeleteFile(remoteFile);
  965. }
  966. StreamWriter sw = null;
  967. try
  968. {
  969. sw = client.CreateText(remoteFile);
  970. Assert.Fail();
  971. }
  972. catch (SftpPathNotFoundException ex)
  973. {
  974. Assert.IsNull(ex.InnerException);
  975. Assert.AreEqual("No such file", ex.Message);
  976. }
  977. finally
  978. {
  979. sw?.Dispose();
  980. if (client.Exists(remoteFile))
  981. {
  982. client.DeleteFile(remoteFile);
  983. }
  984. }
  985. }
  986. }
  987. [TestMethod]
  988. public void Sftp_CreateText_NoEncoding_FileDoesNotExist()
  989. {
  990. var encoding = new UTF8Encoding(false, true);
  991. var initialContent = "\u0100ert & Ann";
  992. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  993. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  994. {
  995. client.Connect();
  996. var remoteFile = GenerateUniqueRemoteFileName();
  997. if (client.Exists(remoteFile))
  998. {
  999. client.DeleteFile(remoteFile);
  1000. }
  1001. try
  1002. {
  1003. using (client.CreateText(remoteFile))
  1004. {
  1005. }
  1006. // verify that empty file was created
  1007. Assert.IsTrue(client.Exists(remoteFile));
  1008. var file = client.GetAttributes(remoteFile);
  1009. Assert.AreEqual(0, file.Size);
  1010. client.DeleteFile(remoteFile);
  1011. using (var sw = client.CreateText(remoteFile))
  1012. {
  1013. sw.Write(initialContent);
  1014. }
  1015. // verify that content is written to file
  1016. var text = client.ReadAllText(remoteFile);
  1017. Assert.AreEqual(initialContent, text);
  1018. using (var fs = client.OpenRead(remoteFile))
  1019. {
  1020. var actualBytes = new byte[fs.Length];
  1021. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1022. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1023. }
  1024. }
  1025. finally
  1026. {
  1027. if (client.Exists(remoteFile))
  1028. {
  1029. client.DeleteFile(remoteFile);
  1030. }
  1031. }
  1032. }
  1033. }
  1034. [TestMethod]
  1035. public void Sftp_CreateText_Encoding_ExistingFile()
  1036. {
  1037. var encoding = GetRandomEncoding();
  1038. var initialContent = "\u0100ert & Ann";
  1039. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1040. var newContent = "\u0116ver";
  1041. var expectedContent = "\u0116ver" + " & Ann";
  1042. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  1043. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1044. {
  1045. client.Connect();
  1046. var remoteFile = GenerateUniqueRemoteFileName();
  1047. if (client.Exists(remoteFile))
  1048. {
  1049. client.DeleteFile(remoteFile);
  1050. }
  1051. try
  1052. {
  1053. client.WriteAllText(remoteFile, initialContent, encoding);
  1054. using (client.CreateText(remoteFile))
  1055. {
  1056. }
  1057. // verify that original content is left untouched
  1058. using (var fs = client.OpenRead(remoteFile))
  1059. {
  1060. var actualBytes = new byte[fs.Length];
  1061. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1062. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1063. }
  1064. // write content that is less bytes than original content
  1065. using (var sw = client.CreateText(remoteFile, encoding))
  1066. {
  1067. sw.Write(newContent);
  1068. }
  1069. // verify that original content is only partially overwritten
  1070. var text = client.ReadAllText(remoteFile, encoding);
  1071. Assert.AreEqual(expectedContent, text);
  1072. using (var fs = client.OpenRead(remoteFile))
  1073. {
  1074. var actualBytes = new byte[fs.Length];
  1075. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1076. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  1077. }
  1078. }
  1079. finally
  1080. {
  1081. if (client.Exists(remoteFile))
  1082. {
  1083. client.DeleteFile(remoteFile);
  1084. }
  1085. }
  1086. }
  1087. }
  1088. [TestMethod]
  1089. public void Sftp_CreateText_Encoding_DirectoryDoesNotExist()
  1090. {
  1091. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1092. var encoding = GetRandomEncoding();
  1093. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1094. {
  1095. client.Connect();
  1096. if (client.Exists(remoteFile))
  1097. {
  1098. client.DeleteFile(remoteFile);
  1099. }
  1100. StreamWriter sw = null;
  1101. try
  1102. {
  1103. sw = client.CreateText(remoteFile, encoding);
  1104. Assert.Fail();
  1105. }
  1106. catch (SftpPathNotFoundException ex)
  1107. {
  1108. Assert.IsNull(ex.InnerException);
  1109. Assert.AreEqual("No such file", ex.Message);
  1110. }
  1111. finally
  1112. {
  1113. sw?.Dispose();
  1114. if (client.Exists(remoteFile))
  1115. {
  1116. client.DeleteFile(remoteFile);
  1117. }
  1118. }
  1119. }
  1120. }
  1121. [TestMethod]
  1122. public void Sftp_CreateText_Encoding_FileDoesNotExist()
  1123. {
  1124. var encoding = GetRandomEncoding();
  1125. var initialContent = "\u0100ert & Ann";
  1126. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1127. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1128. {
  1129. client.Connect();
  1130. var remoteFile = GenerateUniqueRemoteFileName();
  1131. if (client.Exists(remoteFile))
  1132. {
  1133. client.DeleteFile(remoteFile);
  1134. }
  1135. try
  1136. {
  1137. using (client.CreateText(remoteFile, encoding))
  1138. {
  1139. }
  1140. // verify that file containing only preamble was created
  1141. Assert.IsTrue(client.Exists(remoteFile));
  1142. var file = client.GetAttributes(remoteFile);
  1143. Assert.AreEqual(encoding.GetPreamble().Length, file.Size);
  1144. client.DeleteFile(remoteFile);
  1145. using (var sw = client.CreateText(remoteFile, encoding))
  1146. {
  1147. sw.Write(initialContent);
  1148. }
  1149. // verify that content is written to file
  1150. var text = client.ReadAllText(remoteFile, encoding);
  1151. Assert.AreEqual(initialContent, text);
  1152. using (var fs = client.OpenRead(remoteFile))
  1153. {
  1154. var actualBytes = new byte[fs.Length];
  1155. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1156. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1157. }
  1158. }
  1159. finally
  1160. {
  1161. if (client.Exists(remoteFile))
  1162. {
  1163. client.DeleteFile(remoteFile);
  1164. }
  1165. }
  1166. }
  1167. }
  1168. [TestMethod]
  1169. public void Sftp_DownloadFile_FileDoesNotExist()
  1170. {
  1171. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1172. {
  1173. client.Connect();
  1174. var remoteFile = GenerateUniqueRemoteFileName();
  1175. if (client.Exists(remoteFile))
  1176. {
  1177. client.DeleteFile(remoteFile);
  1178. }
  1179. using (var ms = new MemoryStream())
  1180. {
  1181. try
  1182. {
  1183. client.DownloadFile(remoteFile, ms);
  1184. Assert.Fail();
  1185. }
  1186. catch (SftpPathNotFoundException ex)
  1187. {
  1188. Assert.IsNull(ex.InnerException);
  1189. Assert.AreEqual("No such file", ex.Message);
  1190. // ensure file was not created by us
  1191. Assert.IsFalse(client.Exists(remoteFile));
  1192. }
  1193. finally
  1194. {
  1195. if (client.Exists(remoteFile))
  1196. {
  1197. client.DeleteFile(remoteFile);
  1198. }
  1199. }
  1200. }
  1201. }
  1202. }
  1203. [TestMethod]
  1204. public void Sftp_ReadAllBytes_ExistingFile()
  1205. {
  1206. var encoding = GetRandomEncoding();
  1207. var content = "\u0100ert & Ann";
  1208. var contentBytes = GetBytesWithPreamble(content, encoding);
  1209. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1210. {
  1211. client.Connect();
  1212. var remoteFile = GenerateUniqueRemoteFileName();
  1213. if (client.Exists(remoteFile))
  1214. {
  1215. client.DeleteFile(remoteFile);
  1216. }
  1217. try
  1218. {
  1219. client.WriteAllText(remoteFile, content, encoding);
  1220. var actualBytes = client.ReadAllBytes(remoteFile);
  1221. Assert.IsTrue(contentBytes.IsEqualTo(actualBytes));
  1222. }
  1223. finally
  1224. {
  1225. if (client.Exists(remoteFile))
  1226. {
  1227. client.DeleteFile(remoteFile);
  1228. }
  1229. }
  1230. }
  1231. }
  1232. [TestMethod]
  1233. public void Sftp_ReadAllBytes_FileDoesNotExist()
  1234. {
  1235. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1236. {
  1237. client.Connect();
  1238. var remoteFile = GenerateUniqueRemoteFileName();
  1239. if (client.Exists(remoteFile))
  1240. {
  1241. client.DeleteFile(remoteFile);
  1242. }
  1243. try
  1244. {
  1245. client.ReadAllBytes(remoteFile);
  1246. Assert.Fail();
  1247. }
  1248. catch (SftpPathNotFoundException ex)
  1249. {
  1250. Assert.IsNull(ex.InnerException);
  1251. Assert.AreEqual("No such file", ex.Message);
  1252. // ensure file was not created by us
  1253. Assert.IsFalse(client.Exists(remoteFile));
  1254. }
  1255. finally
  1256. {
  1257. if (client.Exists(remoteFile))
  1258. {
  1259. client.DeleteFile(remoteFile);
  1260. }
  1261. }
  1262. }
  1263. }
  1264. [TestMethod]
  1265. public void Sftp_ReadAllLines_NoEncoding_ExistingFile()
  1266. {
  1267. var encoding = new UTF8Encoding(false, true);
  1268. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1269. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1270. encoding);
  1271. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1272. {
  1273. client.Connect();
  1274. var remoteFile = GenerateUniqueRemoteFileName();
  1275. if (client.Exists(remoteFile))
  1276. {
  1277. client.DeleteFile(remoteFile);
  1278. }
  1279. try
  1280. {
  1281. using (var sw = client.AppendText(remoteFile))
  1282. {
  1283. for (var i = 0; i < lines.Length; i++)
  1284. {
  1285. sw.WriteLine(lines[i]);
  1286. }
  1287. }
  1288. var actualLines = client.ReadAllLines(remoteFile);
  1289. Assert.IsNotNull(actualLines);
  1290. Assert.AreEqual(lines.Length, actualLines.Length);
  1291. for (var i = 0; i < lines.Length; i++)
  1292. {
  1293. Assert.AreEqual(lines[i], actualLines[i]);
  1294. }
  1295. using (var fs = client.OpenRead(remoteFile))
  1296. {
  1297. var actualBytes = new byte[fs.Length];
  1298. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1299. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1300. }
  1301. }
  1302. finally
  1303. {
  1304. if (client.Exists(remoteFile))
  1305. {
  1306. client.DeleteFile(remoteFile);
  1307. }
  1308. }
  1309. }
  1310. }
  1311. [TestMethod]
  1312. public void Sftp_ReadAllLines_NoEncoding_FileDoesNotExist()
  1313. {
  1314. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1315. {
  1316. client.Connect();
  1317. var remoteFile = GenerateUniqueRemoteFileName();
  1318. if (client.Exists(remoteFile))
  1319. {
  1320. client.DeleteFile(remoteFile);
  1321. }
  1322. try
  1323. {
  1324. client.ReadAllLines(remoteFile);
  1325. Assert.Fail();
  1326. }
  1327. catch (SftpPathNotFoundException ex)
  1328. {
  1329. Assert.IsNull(ex.InnerException);
  1330. Assert.AreEqual("No such file", ex.Message);
  1331. // ensure file was not created by us
  1332. Assert.IsFalse(client.Exists(remoteFile));
  1333. }
  1334. finally
  1335. {
  1336. if (client.Exists(remoteFile))
  1337. {
  1338. client.DeleteFile(remoteFile);
  1339. }
  1340. }
  1341. }
  1342. }
  1343. [TestMethod]
  1344. public void Sftp_ReadAllLines_Encoding_ExistingFile()
  1345. {
  1346. var encoding = GetRandomEncoding();
  1347. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1348. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1349. encoding);
  1350. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1351. {
  1352. client.Connect();
  1353. var remoteFile = GenerateUniqueRemoteFileName();
  1354. if (client.Exists(remoteFile))
  1355. {
  1356. client.DeleteFile(remoteFile);
  1357. }
  1358. try
  1359. {
  1360. using (var sw = client.AppendText(remoteFile, encoding))
  1361. {
  1362. for (var i = 0; i < lines.Length; i++)
  1363. {
  1364. sw.WriteLine(lines[i]);
  1365. }
  1366. }
  1367. var actualLines = client.ReadAllLines(remoteFile, encoding);
  1368. Assert.IsNotNull(actualLines);
  1369. Assert.AreEqual(lines.Length, actualLines.Length);
  1370. for (var i = 0; i < lines.Length; i++)
  1371. {
  1372. Assert.AreEqual(lines[i], actualLines[i]);
  1373. }
  1374. using (var fs = client.OpenRead(remoteFile))
  1375. {
  1376. var actualBytes = new byte[fs.Length];
  1377. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1378. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1379. }
  1380. }
  1381. finally
  1382. {
  1383. if (client.Exists(remoteFile))
  1384. {
  1385. client.DeleteFile(remoteFile);
  1386. }
  1387. }
  1388. }
  1389. }
  1390. [TestMethod]
  1391. public void Sftp_ReadAllLines_Encoding_FileDoesNotExist()
  1392. {
  1393. var encoding = GetRandomEncoding();
  1394. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1395. {
  1396. client.Connect();
  1397. var remoteFile = GenerateUniqueRemoteFileName();
  1398. if (client.Exists(remoteFile))
  1399. {
  1400. client.DeleteFile(remoteFile);
  1401. }
  1402. try
  1403. {
  1404. client.ReadAllLines(remoteFile, encoding);
  1405. Assert.Fail();
  1406. }
  1407. catch (SftpPathNotFoundException ex)
  1408. {
  1409. Assert.IsNull(ex.InnerException);
  1410. Assert.AreEqual("No such file", ex.Message);
  1411. // ensure file was not created by us
  1412. Assert.IsFalse(client.Exists(remoteFile));
  1413. }
  1414. finally
  1415. {
  1416. if (client.Exists(remoteFile))
  1417. {
  1418. client.DeleteFile(remoteFile);
  1419. }
  1420. }
  1421. }
  1422. }
  1423. [TestMethod]
  1424. public void Sftp_ReadAllText_NoEncoding_ExistingFile()
  1425. {
  1426. var encoding = new UTF8Encoding(false, true);
  1427. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1428. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1429. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1430. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1431. {
  1432. client.Connect();
  1433. var remoteFile = GenerateUniqueRemoteFileName();
  1434. if (client.Exists(remoteFile))
  1435. {
  1436. client.DeleteFile(remoteFile);
  1437. }
  1438. try
  1439. {
  1440. using (var sw = client.AppendText(remoteFile))
  1441. {
  1442. for (var i = 0; i < lines.Length; i++)
  1443. {
  1444. sw.WriteLine(lines[i]);
  1445. }
  1446. }
  1447. var actualText = client.ReadAllText(remoteFile);
  1448. Assert.AreEqual(actualText, expectedText);
  1449. using (var fs = client.OpenRead(remoteFile))
  1450. {
  1451. var actualBytes = new byte[fs.Length];
  1452. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1453. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1454. }
  1455. }
  1456. finally
  1457. {
  1458. if (client.Exists(remoteFile))
  1459. {
  1460. client.DeleteFile(remoteFile);
  1461. }
  1462. }
  1463. }
  1464. }
  1465. [TestMethod]
  1466. public void Sftp_ReadAllText_NoEncoding_FileDoesNotExist()
  1467. {
  1468. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1469. {
  1470. client.Connect();
  1471. var remoteFile = GenerateUniqueRemoteFileName();
  1472. if (client.Exists(remoteFile))
  1473. {
  1474. client.DeleteFile(remoteFile);
  1475. }
  1476. try
  1477. {
  1478. client.ReadAllText(remoteFile);
  1479. Assert.Fail();
  1480. }
  1481. catch (SftpPathNotFoundException ex)
  1482. {
  1483. Assert.IsNull(ex.InnerException);
  1484. Assert.AreEqual("No such file", ex.Message);
  1485. // ensure file was not created by us
  1486. Assert.IsFalse(client.Exists(remoteFile));
  1487. }
  1488. finally
  1489. {
  1490. if (client.Exists(remoteFile))
  1491. {
  1492. client.DeleteFile(remoteFile);
  1493. }
  1494. }
  1495. }
  1496. }
  1497. [TestMethod]
  1498. public void Sftp_ReadAllText_Encoding_ExistingFile()
  1499. {
  1500. var encoding = GetRandomEncoding();
  1501. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1502. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1503. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1504. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1505. {
  1506. client.Connect();
  1507. var remoteFile = GenerateUniqueRemoteFileName();
  1508. if (client.Exists(remoteFile))
  1509. {
  1510. client.DeleteFile(remoteFile);
  1511. }
  1512. try
  1513. {
  1514. using (var sw = client.AppendText(remoteFile, encoding))
  1515. {
  1516. for (var i = 0; i < lines.Length; i++)
  1517. {
  1518. sw.WriteLine(lines[i]);
  1519. }
  1520. }
  1521. var actualText = client.ReadAllText(remoteFile, encoding);
  1522. Assert.AreEqual(expectedText, actualText);
  1523. using (var fs = client.OpenRead(remoteFile))
  1524. {
  1525. var actualBytes = new byte[fs.Length];
  1526. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1527. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1528. }
  1529. }
  1530. finally
  1531. {
  1532. if (client.Exists(remoteFile))
  1533. {
  1534. client.DeleteFile(remoteFile);
  1535. }
  1536. }
  1537. }
  1538. }
  1539. [TestMethod]
  1540. public void Sftp_ReadAllText_Encoding_FileDoesNotExist()
  1541. {
  1542. var encoding = GetRandomEncoding();
  1543. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1544. {
  1545. client.Connect();
  1546. var remoteFile = GenerateUniqueRemoteFileName();
  1547. if (client.Exists(remoteFile))
  1548. {
  1549. client.DeleteFile(remoteFile);
  1550. }
  1551. try
  1552. {
  1553. client.ReadAllText(remoteFile, encoding);
  1554. Assert.Fail();
  1555. }
  1556. catch (SftpPathNotFoundException ex)
  1557. {
  1558. Assert.IsNull(ex.InnerException);
  1559. Assert.AreEqual("No such file", ex.Message);
  1560. // ensure file was not created by us
  1561. Assert.IsFalse(client.Exists(remoteFile));
  1562. }
  1563. finally
  1564. {
  1565. if (client.Exists(remoteFile))
  1566. {
  1567. client.DeleteFile(remoteFile);
  1568. }
  1569. }
  1570. }
  1571. }
  1572. [TestMethod]
  1573. public void Sftp_ReadLines_NoEncoding_ExistingFile()
  1574. {
  1575. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1576. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1577. {
  1578. client.Connect();
  1579. var remoteFile = GenerateUniqueRemoteFileName();
  1580. if (client.Exists(remoteFile))
  1581. {
  1582. client.DeleteFile(remoteFile);
  1583. }
  1584. try
  1585. {
  1586. using (var sw = client.AppendText(remoteFile))
  1587. {
  1588. for (var i = 0; i < lines.Length; i++)
  1589. {
  1590. sw.WriteLine(lines[i]);
  1591. }
  1592. }
  1593. var actualLines = client.ReadLines(remoteFile);
  1594. Assert.IsNotNull(actualLines);
  1595. var actualLinesEnum = actualLines.GetEnumerator();
  1596. for (var i = 0; i < lines.Length; i++)
  1597. {
  1598. Assert.IsTrue(actualLinesEnum.MoveNext());
  1599. var actualLine = actualLinesEnum.Current;
  1600. Assert.AreEqual(lines[i], actualLine);
  1601. }
  1602. Assert.IsFalse(actualLinesEnum.MoveNext());
  1603. }
  1604. finally
  1605. {
  1606. if (client.Exists(remoteFile))
  1607. {
  1608. client.DeleteFile(remoteFile);
  1609. }
  1610. }
  1611. }
  1612. }
  1613. [TestMethod]
  1614. public void Sftp_ReadLines_NoEncoding_FileDoesNotExist()
  1615. {
  1616. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1617. {
  1618. client.Connect();
  1619. var remoteFile = GenerateUniqueRemoteFileName();
  1620. if (client.Exists(remoteFile))
  1621. {
  1622. client.DeleteFile(remoteFile);
  1623. }
  1624. try
  1625. {
  1626. client.ReadLines(remoteFile);
  1627. Assert.Fail();
  1628. }
  1629. catch (SftpPathNotFoundException ex)
  1630. {
  1631. Assert.IsNull(ex.InnerException);
  1632. Assert.AreEqual("No such file", ex.Message);
  1633. // ensure file was not created by us
  1634. Assert.IsFalse(client.Exists(remoteFile));
  1635. }
  1636. finally
  1637. {
  1638. if (client.Exists(remoteFile))
  1639. {
  1640. client.DeleteFile(remoteFile);
  1641. }
  1642. }
  1643. }
  1644. }
  1645. [TestMethod]
  1646. public void Sftp_ReadLines_Encoding_ExistingFile()
  1647. {
  1648. var encoding = GetRandomEncoding();
  1649. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1650. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1651. {
  1652. client.Connect();
  1653. var remoteFile = GenerateUniqueRemoteFileName();
  1654. if (client.Exists(remoteFile))
  1655. {
  1656. client.DeleteFile(remoteFile);
  1657. }
  1658. try
  1659. {
  1660. using (var sw = client.AppendText(remoteFile, encoding))
  1661. {
  1662. for (var i = 0; i < lines.Length; i++)
  1663. {
  1664. sw.WriteLine(lines[i]);
  1665. }
  1666. }
  1667. var actualLines = client.ReadLines(remoteFile, encoding);
  1668. Assert.IsNotNull(actualLines);
  1669. using (var actualLinesEnum = actualLines.GetEnumerator())
  1670. {
  1671. for (var i = 0; i < lines.Length; i++)
  1672. {
  1673. Assert.IsTrue(actualLinesEnum.MoveNext());
  1674. var actualLine = actualLinesEnum.Current;
  1675. Assert.AreEqual(lines[i], actualLine);
  1676. }
  1677. Assert.IsFalse(actualLinesEnum.MoveNext());
  1678. }
  1679. }
  1680. finally
  1681. {
  1682. if (client.Exists(remoteFile))
  1683. {
  1684. client.DeleteFile(remoteFile);
  1685. }
  1686. }
  1687. }
  1688. }
  1689. [TestMethod]
  1690. public void Sftp_ReadLines_Encoding_FileDoesNotExist()
  1691. {
  1692. var encoding = GetRandomEncoding();
  1693. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1694. {
  1695. client.Connect();
  1696. var remoteFile = GenerateUniqueRemoteFileName();
  1697. if (client.Exists(remoteFile))
  1698. {
  1699. client.DeleteFile(remoteFile);
  1700. }
  1701. try
  1702. {
  1703. client.ReadLines(remoteFile, encoding);
  1704. Assert.Fail();
  1705. }
  1706. catch (SftpPathNotFoundException ex)
  1707. {
  1708. Assert.IsNull(ex.InnerException);
  1709. Assert.AreEqual("No such file", ex.Message);
  1710. // ensure file was not created by us
  1711. Assert.IsFalse(client.Exists(remoteFile));
  1712. }
  1713. finally
  1714. {
  1715. if (client.Exists(remoteFile))
  1716. {
  1717. client.DeleteFile(remoteFile);
  1718. }
  1719. }
  1720. }
  1721. }
  1722. [TestMethod]
  1723. public void Sftp_WriteAllBytes_DirectoryDoesNotExist()
  1724. {
  1725. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1726. var content = GenerateRandom(size: 5);
  1727. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1728. {
  1729. client.Connect();
  1730. if (client.Exists(remoteFile))
  1731. {
  1732. client.DeleteFile(remoteFile);
  1733. }
  1734. try
  1735. {
  1736. client.WriteAllBytes(remoteFile, content);
  1737. Assert.Fail();
  1738. }
  1739. catch (SftpPathNotFoundException ex)
  1740. {
  1741. Assert.IsNull(ex.InnerException);
  1742. Assert.AreEqual("No such file", ex.Message);
  1743. }
  1744. finally
  1745. {
  1746. if (client.Exists(remoteFile))
  1747. {
  1748. client.DeleteFile(remoteFile);
  1749. }
  1750. }
  1751. }
  1752. }
  1753. [TestMethod]
  1754. public void Sftp_WriteAllBytes_ExistingFile()
  1755. {
  1756. var initialContent = GenerateRandom(size: 13);
  1757. var newContent1 = GenerateRandom(size: 5);
  1758. var expectedContent1 = new ArrayBuilder<byte>().Add(newContent1)
  1759. .Add(initialContent, newContent1.Length, initialContent.Length - newContent1.Length)
  1760. .Build();
  1761. var newContent2 = GenerateRandom(size: 50000);
  1762. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1763. {
  1764. client.Connect();
  1765. var remoteFile = GenerateUniqueRemoteFileName();
  1766. if (client.Exists(remoteFile))
  1767. {
  1768. client.DeleteFile(remoteFile);
  1769. }
  1770. try
  1771. {
  1772. using (var fs = client.Create(remoteFile))
  1773. {
  1774. fs.Write(initialContent, offset: 0, initialContent.Length);
  1775. }
  1776. #region Write less bytes than the current content, overwriting part of that content
  1777. client.WriteAllBytes(remoteFile, newContent1);
  1778. var actualContent1 = client.ReadAllBytes(remoteFile);
  1779. Assert.IsTrue(expectedContent1.IsEqualTo(actualContent1));
  1780. #endregion Write less bytes than the initial content, overwriting part of that content
  1781. #region Write more bytes than the current content, overwriting and appending to that content
  1782. client.WriteAllBytes(remoteFile, newContent2);
  1783. var actualContent2 = client.ReadAllBytes(remoteFile);
  1784. Assert.IsTrue(newContent2.IsEqualTo(actualContent2));
  1785. #endregion Write less bytes than the initial content, overwriting part of that content
  1786. }
  1787. finally
  1788. {
  1789. if (client.Exists(remoteFile))
  1790. {
  1791. client.DeleteFile(remoteFile);
  1792. }
  1793. }
  1794. }
  1795. }
  1796. [TestMethod]
  1797. public void Sftp_WriteAllBytes_FileDoesNotExist()
  1798. {
  1799. var content = GenerateRandom(size: 13);
  1800. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1801. {
  1802. client.Connect();
  1803. var remoteFile = GenerateUniqueRemoteFileName();
  1804. if (client.Exists(remoteFile))
  1805. {
  1806. client.DeleteFile(remoteFile);
  1807. }
  1808. try
  1809. {
  1810. client.WriteAllBytes(remoteFile, content);
  1811. using (var fs = client.OpenRead(remoteFile))
  1812. {
  1813. var actualBytes = new byte[fs.Length];
  1814. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1815. Assert.IsTrue(content.IsEqualTo(actualBytes));
  1816. }
  1817. }
  1818. finally
  1819. {
  1820. if (client.Exists(remoteFile))
  1821. {
  1822. client.DeleteFile(remoteFile);
  1823. }
  1824. }
  1825. }
  1826. }
  1827. [TestMethod]
  1828. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_DirectoryDoesNotExist()
  1829. {
  1830. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1831. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1832. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1833. {
  1834. client.Connect();
  1835. if (client.Exists(remoteFile))
  1836. {
  1837. client.DeleteFile(remoteFile);
  1838. }
  1839. try
  1840. {
  1841. client.WriteAllLines(remoteFile, linesToWrite);
  1842. Assert.Fail();
  1843. }
  1844. catch (SftpPathNotFoundException ex)
  1845. {
  1846. Assert.IsNull(ex.InnerException);
  1847. Assert.AreEqual("No such file", ex.Message);
  1848. }
  1849. finally
  1850. {
  1851. if (client.Exists(remoteFile))
  1852. {
  1853. client.DeleteFile(remoteFile);
  1854. }
  1855. }
  1856. }
  1857. }
  1858. [TestMethod]
  1859. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_ExistingFile()
  1860. {
  1861. var encoding = new UTF8Encoding(false, true);
  1862. var initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1863. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1864. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1865. var linesToWrite1Bytes =
  1866. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1867. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  1868. .Add(initialContentBytes,
  1869. linesToWrite1Bytes.Length,
  1870. initialContentBytes.Length - linesToWrite1Bytes.Length)
  1871. .Build();
  1872. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1873. var linesToWrite2Bytes =
  1874. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1875. var expectedBytes2 = linesToWrite2Bytes;
  1876. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1877. {
  1878. client.Connect();
  1879. var remoteFile = GenerateUniqueRemoteFileName();
  1880. if (client.Exists(remoteFile))
  1881. {
  1882. client.DeleteFile(remoteFile);
  1883. }
  1884. try
  1885. {
  1886. // create initial content
  1887. client.WriteAllText(remoteFile, initialContent);
  1888. #region Write less bytes than the current content, overwriting part of that content
  1889. client.WriteAllLines(remoteFile, linesToWrite1);
  1890. using (var fs = client.OpenRead(remoteFile))
  1891. {
  1892. var actualBytes = new byte[fs.Length];
  1893. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1894. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  1895. }
  1896. #endregion Write less bytes than the current content, overwriting part of that content
  1897. #region Write more bytes than the current content, overwriting and appending to that content
  1898. client.WriteAllLines(remoteFile, linesToWrite2);
  1899. using (var fs = client.OpenRead(remoteFile))
  1900. {
  1901. var actualBytes = new byte[fs.Length];
  1902. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1903. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  1904. }
  1905. #endregion Write more bytes than the current content, overwriting and appending to that content
  1906. }
  1907. finally
  1908. {
  1909. if (client.Exists(remoteFile))
  1910. {
  1911. client.DeleteFile(remoteFile);
  1912. }
  1913. }
  1914. }
  1915. }
  1916. [TestMethod]
  1917. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_FileDoesNotExist()
  1918. {
  1919. var encoding = new UTF8Encoding(false, true);
  1920. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1921. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1922. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1923. {
  1924. client.Connect();
  1925. var remoteFile = GenerateUniqueRemoteFileName();
  1926. if (client.Exists(remoteFile))
  1927. {
  1928. client.DeleteFile(remoteFile);
  1929. }
  1930. try
  1931. {
  1932. client.WriteAllLines(remoteFile, linesToWrite);
  1933. using (var fs = client.OpenRead(remoteFile))
  1934. {
  1935. var actualBytes = new byte[fs.Length];
  1936. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1937. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  1938. }
  1939. }
  1940. finally
  1941. {
  1942. if (client.Exists(remoteFile))
  1943. {
  1944. client.DeleteFile(remoteFile);
  1945. }
  1946. }
  1947. }
  1948. }
  1949. [TestMethod]
  1950. public void Sftp_WriteAllLines_IEnumerable_Encoding_DirectoryDoesNotExist()
  1951. {
  1952. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1953. var encoding = GetRandomEncoding();
  1954. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1955. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1956. {
  1957. client.Connect();
  1958. if (client.Exists(remoteFile))
  1959. {
  1960. client.DeleteFile(remoteFile);
  1961. }
  1962. try
  1963. {
  1964. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1965. Assert.Fail();
  1966. }
  1967. catch (SftpPathNotFoundException ex)
  1968. {
  1969. Assert.IsNull(ex.InnerException);
  1970. Assert.AreEqual("No such file", ex.Message);
  1971. }
  1972. finally
  1973. {
  1974. if (client.Exists(remoteFile))
  1975. {
  1976. client.DeleteFile(remoteFile);
  1977. }
  1978. }
  1979. }
  1980. }
  1981. [TestMethod]
  1982. public void Sftp_WriteAllLines_IEnumerable_Encoding_ExistingFile()
  1983. {
  1984. var encoding = GetRandomEncoding();
  1985. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1986. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1987. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1988. var linesToWrite1Bytes =
  1989. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1990. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  1991. .Add(initialContentBytes,
  1992. linesToWrite1Bytes.Length,
  1993. initialContentBytes.Length - linesToWrite1Bytes.Length)
  1994. .Build();
  1995. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1996. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1997. var expectedBytes2 = linesToWrite2Bytes;
  1998. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1999. {
  2000. client.Connect();
  2001. var remoteFile = GenerateUniqueRemoteFileName();
  2002. if (client.Exists(remoteFile))
  2003. {
  2004. client.DeleteFile(remoteFile);
  2005. }
  2006. try
  2007. {
  2008. // create initial content
  2009. client.WriteAllText(remoteFile, initialContent, encoding);
  2010. #region Write less bytes than the current content, overwriting part of that content
  2011. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2012. using (var fs = client.OpenRead(remoteFile))
  2013. {
  2014. var actualBytes = new byte[fs.Length];
  2015. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2016. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2017. }
  2018. #endregion Write less bytes than the current content, overwriting part of that content
  2019. #region Write more bytes than the current content, overwriting and appending to that content
  2020. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2021. using (var fs = client.OpenRead(remoteFile))
  2022. {
  2023. var actualBytes = new byte[fs.Length];
  2024. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2025. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2026. }
  2027. #endregion Write more bytes than the current content, overwriting and appending to that content
  2028. }
  2029. finally
  2030. {
  2031. if (client.Exists(remoteFile))
  2032. {
  2033. client.DeleteFile(remoteFile);
  2034. }
  2035. }
  2036. }
  2037. }
  2038. [TestMethod]
  2039. public void Sftp_WriteAllLines_IEnumerable_Encoding_FileDoesNotExist()
  2040. {
  2041. var encoding = GetRandomEncoding();
  2042. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2043. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2044. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2045. {
  2046. client.Connect();
  2047. var remoteFile = GenerateUniqueRemoteFileName();
  2048. if (client.Exists(remoteFile))
  2049. {
  2050. client.DeleteFile(remoteFile);
  2051. }
  2052. try
  2053. {
  2054. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2055. using (var fs = client.OpenRead(remoteFile))
  2056. {
  2057. var actualBytes = new byte[fs.Length];
  2058. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2059. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2060. }
  2061. }
  2062. finally
  2063. {
  2064. if (client.Exists(remoteFile))
  2065. {
  2066. client.DeleteFile(remoteFile);
  2067. }
  2068. }
  2069. }
  2070. }
  2071. [TestMethod]
  2072. public void Sftp_WriteAllLines_Array_NoEncoding_DirectoryDoesNotExist()
  2073. {
  2074. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2075. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2076. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2077. {
  2078. client.Connect();
  2079. if (client.Exists(remoteFile))
  2080. {
  2081. client.DeleteFile(remoteFile);
  2082. }
  2083. try
  2084. {
  2085. client.WriteAllLines(remoteFile, linesToWrite);
  2086. Assert.Fail();
  2087. }
  2088. catch (SftpPathNotFoundException ex)
  2089. {
  2090. Assert.IsNull(ex.InnerException);
  2091. Assert.AreEqual("No such file", ex.Message);
  2092. }
  2093. finally
  2094. {
  2095. if (client.Exists(remoteFile))
  2096. {
  2097. client.DeleteFile(remoteFile);
  2098. }
  2099. }
  2100. }
  2101. }
  2102. [TestMethod]
  2103. public void Sftp_WriteAllLines_Array_NoEncoding_ExistingFile()
  2104. {
  2105. var encoding = new UTF8Encoding(false, true);
  2106. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2107. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2108. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2109. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2110. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2111. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2112. .Build();
  2113. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2114. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2115. var expectedBytes2 = linesToWrite2Bytes;
  2116. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2117. {
  2118. client.Connect();
  2119. var remoteFile = GenerateUniqueRemoteFileName();
  2120. if (client.Exists(remoteFile))
  2121. {
  2122. client.DeleteFile(remoteFile);
  2123. }
  2124. try
  2125. {
  2126. // create initial content
  2127. client.WriteAllText(remoteFile, initialContent);
  2128. #region Write less bytes than the current content, overwriting part of that content
  2129. client.WriteAllLines(remoteFile, linesToWrite1);
  2130. using (var fs = client.OpenRead(remoteFile))
  2131. {
  2132. var actualBytes = new byte[fs.Length];
  2133. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2134. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2135. }
  2136. #endregion Write less bytes than the current content, overwriting part of that content
  2137. #region Write more bytes than the current content, overwriting and appending to that content
  2138. client.WriteAllLines(remoteFile, linesToWrite2);
  2139. using (var fs = client.OpenRead(remoteFile))
  2140. {
  2141. var actualBytes = new byte[fs.Length];
  2142. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2143. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2144. }
  2145. #endregion Write more bytes than the current content, overwriting and appending to that content
  2146. }
  2147. finally
  2148. {
  2149. if (client.Exists(remoteFile))
  2150. {
  2151. client.DeleteFile(remoteFile);
  2152. }
  2153. }
  2154. }
  2155. }
  2156. [TestMethod]
  2157. public void Sftp_WriteAllLines_Array_NoEncoding_FileDoesNotExist()
  2158. {
  2159. var encoding = new UTF8Encoding(false, true);
  2160. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2161. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2162. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2163. {
  2164. client.Connect();
  2165. var remoteFile = GenerateUniqueRemoteFileName();
  2166. if (client.Exists(remoteFile))
  2167. {
  2168. client.DeleteFile(remoteFile);
  2169. }
  2170. try
  2171. {
  2172. client.WriteAllLines(remoteFile, linesToWrite);
  2173. using (var fs = client.OpenRead(remoteFile))
  2174. {
  2175. var actualBytes = new byte[fs.Length];
  2176. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2177. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2178. }
  2179. }
  2180. finally
  2181. {
  2182. if (client.Exists(remoteFile))
  2183. {
  2184. client.DeleteFile(remoteFile);
  2185. }
  2186. }
  2187. }
  2188. }
  2189. [TestMethod]
  2190. public void Sftp_WriteAllLines_Array_Encoding_DirectoryDoesNotExist()
  2191. {
  2192. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2193. var encoding = GetRandomEncoding();
  2194. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2195. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2196. {
  2197. client.Connect();
  2198. if (client.Exists(remoteFile))
  2199. {
  2200. client.DeleteFile(remoteFile);
  2201. }
  2202. try
  2203. {
  2204. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2205. Assert.Fail();
  2206. }
  2207. catch (SftpPathNotFoundException ex)
  2208. {
  2209. Assert.IsNull(ex.InnerException);
  2210. Assert.AreEqual("No such file", ex.Message);
  2211. }
  2212. finally
  2213. {
  2214. if (client.Exists(remoteFile))
  2215. {
  2216. client.DeleteFile(remoteFile);
  2217. }
  2218. }
  2219. }
  2220. }
  2221. [TestMethod]
  2222. public void Sftp_WriteAllLines_Array_Encoding_ExistingFile()
  2223. {
  2224. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2225. var encoding = GetRandomEncoding();
  2226. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2227. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2228. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2229. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2230. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2231. .Build();
  2232. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2233. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2234. var expectedBytes2 = linesToWrite2Bytes;
  2235. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2236. {
  2237. client.Connect();
  2238. var remoteFile = GenerateUniqueRemoteFileName();
  2239. if (client.Exists(remoteFile))
  2240. {
  2241. client.DeleteFile(remoteFile);
  2242. }
  2243. try
  2244. {
  2245. // create initial content
  2246. client.WriteAllText(remoteFile, initialContent, encoding);
  2247. #region Write less bytes than the current content, overwriting part of that content
  2248. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2249. using (var fs = client.OpenRead(remoteFile))
  2250. {
  2251. var actualBytes = new byte[fs.Length];
  2252. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2253. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2254. }
  2255. #endregion Write less bytes than the current content, overwriting part of that content
  2256. #region Write more bytes than the current content, overwriting and appending to that content
  2257. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2258. using (var fs = client.OpenRead(remoteFile))
  2259. {
  2260. var actualBytes = new byte[fs.Length];
  2261. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2262. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2263. }
  2264. #endregion Write more bytes than the current content, overwriting and appending to that content
  2265. }
  2266. finally
  2267. {
  2268. if (client.Exists(remoteFile))
  2269. {
  2270. client.DeleteFile(remoteFile);
  2271. }
  2272. }
  2273. }
  2274. }
  2275. [TestMethod]
  2276. public void Sftp_WriteAllLines_Array_Encoding_FileDoesNotExist()
  2277. {
  2278. var encoding = GetRandomEncoding();
  2279. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2280. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2281. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2282. {
  2283. client.Connect();
  2284. var remoteFile = GenerateUniqueRemoteFileName();
  2285. if (client.Exists(remoteFile))
  2286. {
  2287. client.DeleteFile(remoteFile);
  2288. }
  2289. try
  2290. {
  2291. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2292. using (var fs = client.OpenRead(remoteFile))
  2293. {
  2294. var actualBytes = new byte[fs.Length];
  2295. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2296. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2297. }
  2298. }
  2299. finally
  2300. {
  2301. if (client.Exists(remoteFile))
  2302. {
  2303. client.DeleteFile(remoteFile);
  2304. }
  2305. }
  2306. }
  2307. }
  2308. [TestMethod]
  2309. public void Sftp_WriteAllText_NoEncoding_DirectoryDoesNotExist()
  2310. {
  2311. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2312. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2313. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2314. {
  2315. client.Connect();
  2316. if (client.Exists(remoteFile))
  2317. {
  2318. client.DeleteFile(remoteFile);
  2319. }
  2320. try
  2321. {
  2322. client.WriteAllText(remoteFile, initialContent);
  2323. Assert.Fail();
  2324. }
  2325. catch (SftpPathNotFoundException ex)
  2326. {
  2327. Assert.IsNull(ex.InnerException);
  2328. Assert.AreEqual("No such file", ex.Message);
  2329. }
  2330. finally
  2331. {
  2332. if (client.Exists(remoteFile))
  2333. {
  2334. client.DeleteFile(remoteFile);
  2335. }
  2336. }
  2337. }
  2338. }
  2339. [TestMethod]
  2340. public void Sftp_WriteAllText_NoEncoding_ExistingFile()
  2341. {
  2342. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2343. const string newContent1 = "For\u0116ver & Ever";
  2344. var encoding = new UTF8Encoding(false, true);
  2345. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2346. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2347. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2348. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2349. .Build();
  2350. var newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2351. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2352. var expectedBytes2 = newContent2Bytes;
  2353. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2354. {
  2355. client.Connect();
  2356. var remoteFile = GenerateUniqueRemoteFileName();
  2357. if (client.Exists(remoteFile))
  2358. {
  2359. client.DeleteFile(remoteFile);
  2360. }
  2361. try
  2362. {
  2363. client.WriteAllText(remoteFile, initialContent);
  2364. #region Write less bytes than the current content, overwriting part of that content
  2365. client.WriteAllText(remoteFile, newContent1);
  2366. using (var fs = client.OpenRead(remoteFile))
  2367. {
  2368. var actualBytes = new byte[fs.Length];
  2369. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2370. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2371. }
  2372. #endregion Write less bytes than the current content, overwriting part of that content
  2373. #region Write more bytes than the current content, overwriting and appending to that content
  2374. client.WriteAllText(remoteFile, newContent2);
  2375. using (var fs = client.OpenRead(remoteFile))
  2376. {
  2377. var actualBytes = new byte[fs.Length];
  2378. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2379. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2380. }
  2381. #endregion Write more bytes than the current content, overwriting and appending to that content
  2382. }
  2383. finally
  2384. {
  2385. if (client.Exists(remoteFile))
  2386. {
  2387. client.DeleteFile(remoteFile);
  2388. }
  2389. }
  2390. }
  2391. }
  2392. [TestMethod]
  2393. public void Sftp_WriteAllText_NoEncoding_FileDoesNotExist()
  2394. {
  2395. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2396. var encoding = new UTF8Encoding(false, true);
  2397. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2398. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2399. {
  2400. client.Connect();
  2401. var remoteFile = GenerateUniqueRemoteFileName();
  2402. if (client.Exists(remoteFile))
  2403. {
  2404. client.DeleteFile(remoteFile);
  2405. }
  2406. try
  2407. {
  2408. client.WriteAllText(remoteFile, initialContent);
  2409. using (var fs = client.OpenRead(remoteFile))
  2410. {
  2411. var actualBytes = new byte[fs.Length];
  2412. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2413. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2414. }
  2415. }
  2416. finally
  2417. {
  2418. if (client.Exists(remoteFile))
  2419. {
  2420. client.DeleteFile(remoteFile);
  2421. }
  2422. }
  2423. }
  2424. }
  2425. [TestMethod]
  2426. public void Sftp_WriteAllText_Encoding_DirectoryDoesNotExist()
  2427. {
  2428. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2429. var encoding = GetRandomEncoding();
  2430. const string content = "For\u0116ver & Ever";
  2431. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2432. {
  2433. client.Connect();
  2434. if (client.Exists(remoteFile))
  2435. {
  2436. client.DeleteFile(remoteFile);
  2437. }
  2438. try
  2439. {
  2440. client.WriteAllText(remoteFile, content, encoding);
  2441. Assert.Fail();
  2442. }
  2443. catch (SftpPathNotFoundException ex)
  2444. {
  2445. Assert.IsNull(ex.InnerException);
  2446. Assert.AreEqual("No such file", ex.Message);
  2447. }
  2448. finally
  2449. {
  2450. if (client.Exists(remoteFile))
  2451. {
  2452. client.DeleteFile(remoteFile);
  2453. }
  2454. }
  2455. }
  2456. }
  2457. [TestMethod]
  2458. public void Sftp_WriteAllText_Encoding_ExistingFile()
  2459. {
  2460. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2461. const string newContent1 = "For\u0116ver & Ever";
  2462. const string newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2463. var encoding = GetRandomEncoding();
  2464. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2465. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2466. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2467. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2468. .Build();
  2469. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2470. var expectedBytes2 = newContent2Bytes;
  2471. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2472. {
  2473. client.Connect();
  2474. var remoteFile = GenerateUniqueRemoteFileName();
  2475. if (client.Exists(remoteFile))
  2476. {
  2477. client.DeleteFile(remoteFile);
  2478. }
  2479. try
  2480. {
  2481. client.WriteAllText(remoteFile, initialContent, encoding);
  2482. #region Write less bytes than the current content, overwriting part of that content
  2483. client.WriteAllText(remoteFile, newContent1, encoding);
  2484. using (var fs = client.OpenRead(remoteFile))
  2485. {
  2486. var actualBytes = new byte[fs.Length];
  2487. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2488. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2489. }
  2490. #endregion Write less bytes than the current content, overwriting part of that content
  2491. #region Write more bytes than the current content, overwriting and appending to that content
  2492. client.WriteAllText(remoteFile, newContent2, encoding);
  2493. using (var fs = client.OpenRead(remoteFile))
  2494. {
  2495. var actualBytes = new byte[fs.Length];
  2496. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2497. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2498. }
  2499. #endregion Write more bytes than the current content, overwriting and appending to that content
  2500. }
  2501. finally
  2502. {
  2503. if (client.Exists(remoteFile))
  2504. {
  2505. client.DeleteFile(remoteFile);
  2506. }
  2507. }
  2508. }
  2509. }
  2510. [TestMethod]
  2511. public void Sftp_WriteAllText_Encoding_FileDoesNotExist()
  2512. {
  2513. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2514. var encoding = GetRandomEncoding();
  2515. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2516. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2517. {
  2518. client.Connect();
  2519. var remoteFile = GenerateUniqueRemoteFileName();
  2520. if (client.Exists(remoteFile))
  2521. {
  2522. client.DeleteFile(remoteFile);
  2523. }
  2524. try
  2525. {
  2526. client.WriteAllText(remoteFile, initialContent, encoding);
  2527. using (var fs = client.OpenRead(remoteFile))
  2528. {
  2529. var actualBytes = new byte[fs.Length];
  2530. fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2531. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2532. }
  2533. }
  2534. finally
  2535. {
  2536. if (client.Exists(remoteFile))
  2537. {
  2538. client.DeleteFile(remoteFile);
  2539. }
  2540. }
  2541. }
  2542. }
  2543. [TestMethod]
  2544. public void Sftp_BeginDownloadFile_FileDoesNotExist()
  2545. {
  2546. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2547. {
  2548. client.Connect();
  2549. var remoteFile = GenerateUniqueRemoteFileName();
  2550. if (client.Exists(remoteFile))
  2551. {
  2552. client.DeleteFile(remoteFile);
  2553. }
  2554. try
  2555. {
  2556. using (var ms = new MemoryStream())
  2557. {
  2558. var asyncResult = client.BeginDownloadFile(remoteFile, ms);
  2559. try
  2560. {
  2561. client.EndDownloadFile(asyncResult);
  2562. Assert.Fail();
  2563. }
  2564. catch (SftpPathNotFoundException ex)
  2565. {
  2566. Assert.IsNull(ex.InnerException);
  2567. Assert.AreEqual("No such file", ex.Message);
  2568. // ensure file was not created by us
  2569. Assert.IsFalse(client.Exists(remoteFile));
  2570. }
  2571. }
  2572. }
  2573. finally
  2574. {
  2575. if (client.Exists(remoteFile))
  2576. {
  2577. client.DeleteFile(remoteFile);
  2578. }
  2579. }
  2580. }
  2581. }
  2582. [TestMethod]
  2583. public void Sftp_BeginListDirectory_DirectoryDoesNotExist()
  2584. {
  2585. const string remoteDirectory = "/home/sshnet/test123";
  2586. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2587. {
  2588. client.Connect();
  2589. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2590. {
  2591. command.Execute();
  2592. }
  2593. }
  2594. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2595. {
  2596. client.Connect();
  2597. var asyncResult = client.BeginListDirectory(remoteDirectory, null, null);
  2598. try
  2599. {
  2600. client.EndListDirectory(asyncResult);
  2601. Assert.Fail();
  2602. }
  2603. catch (SftpPathNotFoundException ex)
  2604. {
  2605. Assert.IsNull(ex.InnerException);
  2606. Assert.AreEqual("No such file", ex.Message);
  2607. // ensure directory was not created by us
  2608. Assert.IsFalse(client.Exists(remoteDirectory));
  2609. }
  2610. }
  2611. }
  2612. [TestMethod]
  2613. public void Sftp_BeginUploadFile_InputAndPath_DirectoryDoesNotExist()
  2614. {
  2615. const int size = 50 * 1024 * 1024;
  2616. const string remoteDirectory = "/home/sshnet/test123";
  2617. const string remoteFile = remoteDirectory + "/test";
  2618. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2619. {
  2620. client.Connect();
  2621. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2622. {
  2623. command.Execute();
  2624. }
  2625. }
  2626. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2627. {
  2628. client.Connect();
  2629. var memoryStream = CreateMemoryStream(size);
  2630. memoryStream.Position = 0;
  2631. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile);
  2632. try
  2633. {
  2634. client.EndUploadFile(asyncResult);
  2635. Assert.Fail();
  2636. }
  2637. catch (SftpPathNotFoundException)
  2638. {
  2639. }
  2640. }
  2641. }
  2642. [TestMethod]
  2643. public void Sftp_BeginUploadFile_InputAndPath_FileDoesNotExist()
  2644. {
  2645. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2646. {
  2647. client.Connect();
  2648. var remoteFile = GenerateUniqueRemoteFileName();
  2649. if (client.Exists(remoteFile))
  2650. {
  2651. client.DeleteFile(remoteFile);
  2652. }
  2653. try
  2654. {
  2655. var uploadMemoryStream = new MemoryStream();
  2656. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2657. sw.Write("Gert & Ann");
  2658. sw.Flush();
  2659. uploadMemoryStream.Position = 0;
  2660. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2661. client.EndUploadFile(asyncResult);
  2662. using (var downloadMemoryStream = new MemoryStream())
  2663. {
  2664. client.DownloadFile(remoteFile, downloadMemoryStream);
  2665. downloadMemoryStream.Position = 0;
  2666. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2667. {
  2668. var content = sr.ReadToEnd();
  2669. Assert.AreEqual("Gert & Ann", content);
  2670. }
  2671. }
  2672. }
  2673. finally
  2674. {
  2675. if (client.Exists(remoteFile))
  2676. {
  2677. client.DeleteFile(remoteFile);
  2678. }
  2679. }
  2680. }
  2681. }
  2682. [TestMethod]
  2683. public void Sftp_BeginUploadFile_InputAndPath_ExistingFile()
  2684. {
  2685. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2686. {
  2687. client.Connect();
  2688. var remoteFile = GenerateUniqueRemoteFileName();
  2689. if (client.Exists(remoteFile))
  2690. {
  2691. client.DeleteFile(remoteFile);
  2692. }
  2693. try
  2694. {
  2695. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2696. var uploadMemoryStream = new MemoryStream();
  2697. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2698. sw.Write("Ann & Gert");
  2699. sw.Flush();
  2700. uploadMemoryStream.Position = 0;
  2701. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2702. client.EndUploadFile(asyncResult);
  2703. using (var downloadMemoryStream = new MemoryStream())
  2704. {
  2705. client.DownloadFile(remoteFile, downloadMemoryStream);
  2706. downloadMemoryStream.Position = 0;
  2707. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2708. {
  2709. var content = sr.ReadToEnd();
  2710. Assert.AreEqual("Ann & Gert", content);
  2711. }
  2712. }
  2713. }
  2714. finally
  2715. {
  2716. if (client.Exists(remoteFile))
  2717. {
  2718. client.DeleteFile(remoteFile);
  2719. }
  2720. }
  2721. }
  2722. }
  2723. [TestMethod]
  2724. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_DirectoryDoesNotExist()
  2725. {
  2726. const int size = 50 * 1024 * 1024;
  2727. const string remoteDirectory = "/home/sshnet/test123";
  2728. const string remoteFile = remoteDirectory + "/test";
  2729. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2730. {
  2731. client.Connect();
  2732. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2733. {
  2734. command.Execute();
  2735. }
  2736. }
  2737. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2738. {
  2739. client.Connect();
  2740. var memoryStream = CreateMemoryStream(size);
  2741. memoryStream.Position = 0;
  2742. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, false, null, null);
  2743. try
  2744. {
  2745. client.EndUploadFile(asyncResult);
  2746. Assert.Fail();
  2747. }
  2748. catch (SftpPathNotFoundException)
  2749. {
  2750. }
  2751. }
  2752. }
  2753. [TestMethod]
  2754. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_FileDoesNotExist()
  2755. {
  2756. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2757. {
  2758. client.Connect();
  2759. var remoteFile = GenerateUniqueRemoteFileName();
  2760. if (client.Exists(remoteFile))
  2761. {
  2762. client.DeleteFile(remoteFile);
  2763. }
  2764. try
  2765. {
  2766. using (var uploadMemoryStream = new MemoryStream())
  2767. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2768. {
  2769. sw.Write("Gert & Ann");
  2770. sw.Flush();
  2771. uploadMemoryStream.Position = 0;
  2772. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2773. client.EndUploadFile(asyncResult);
  2774. }
  2775. using (var downloadMemoryStream = new MemoryStream())
  2776. {
  2777. client.DownloadFile(remoteFile, downloadMemoryStream);
  2778. downloadMemoryStream.Position = 0;
  2779. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2780. {
  2781. var content = sr.ReadToEnd();
  2782. Assert.AreEqual("Gert & Ann", content);
  2783. }
  2784. }
  2785. }
  2786. finally
  2787. {
  2788. if (client.Exists(remoteFile))
  2789. {
  2790. client.DeleteFile(remoteFile);
  2791. }
  2792. }
  2793. }
  2794. }
  2795. [TestMethod]
  2796. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_ExistingFile()
  2797. {
  2798. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2799. {
  2800. client.Connect();
  2801. var remoteFile = GenerateUniqueRemoteFileName();
  2802. if (client.Exists(remoteFile))
  2803. {
  2804. client.DeleteFile(remoteFile);
  2805. }
  2806. try
  2807. {
  2808. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2809. var uploadMemoryStream = new MemoryStream();
  2810. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2811. sw.Write("Ann & Gert");
  2812. sw.Flush();
  2813. uploadMemoryStream.Position = 0;
  2814. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2815. try
  2816. {
  2817. client.EndUploadFile(asyncResult);
  2818. Assert.Fail();
  2819. }
  2820. catch (SshException ex)
  2821. {
  2822. Assert.AreEqual(typeof(SshException), ex.GetType());
  2823. Assert.IsNull(ex.InnerException);
  2824. Assert.AreEqual("Failure", ex.Message);
  2825. }
  2826. }
  2827. finally
  2828. {
  2829. if (client.Exists(remoteFile))
  2830. {
  2831. client.DeleteFile(remoteFile);
  2832. }
  2833. }
  2834. }
  2835. }
  2836. [TestMethod]
  2837. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_DirectoryDoesNotExist()
  2838. {
  2839. const int size = 50 * 1024 * 1024;
  2840. const string remoteDirectory = "/home/sshnet/test123";
  2841. const string remoteFile = remoteDirectory + "/test";
  2842. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2843. {
  2844. client.Connect();
  2845. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2846. {
  2847. command.Execute();
  2848. }
  2849. }
  2850. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2851. {
  2852. client.Connect();
  2853. var memoryStream = CreateMemoryStream(size);
  2854. memoryStream.Position = 0;
  2855. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, true, null, null);
  2856. try
  2857. {
  2858. client.EndUploadFile(asyncResult);
  2859. Assert.Fail();
  2860. }
  2861. catch (SftpPathNotFoundException)
  2862. {
  2863. }
  2864. }
  2865. }
  2866. [TestMethod]
  2867. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_FileDoesNotExist()
  2868. {
  2869. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2870. {
  2871. client.Connect();
  2872. var remoteFile = GenerateUniqueRemoteFileName();
  2873. if (client.Exists(remoteFile))
  2874. {
  2875. client.DeleteFile(remoteFile);
  2876. }
  2877. try
  2878. {
  2879. using (var uploadMemoryStream = new MemoryStream())
  2880. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2881. {
  2882. sw.Write("Gert & Ann");
  2883. sw.Flush();
  2884. uploadMemoryStream.Position = 0;
  2885. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2886. client.EndUploadFile(asyncResult);
  2887. }
  2888. using (var downloadMemoryStream = new MemoryStream())
  2889. {
  2890. client.DownloadFile(remoteFile, downloadMemoryStream);
  2891. downloadMemoryStream.Position = 0;
  2892. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2893. {
  2894. var content = sr.ReadToEnd();
  2895. Assert.AreEqual("Gert & Ann", content);
  2896. }
  2897. }
  2898. }
  2899. finally
  2900. {
  2901. if (client.Exists(remoteFile))
  2902. {
  2903. client.DeleteFile(remoteFile);
  2904. }
  2905. }
  2906. }
  2907. }
  2908. [TestMethod]
  2909. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_ExistingFile()
  2910. {
  2911. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2912. {
  2913. client.Connect();
  2914. var remoteFile = GenerateUniqueRemoteFileName();
  2915. if (client.Exists(remoteFile))
  2916. {
  2917. client.DeleteFile(remoteFile);
  2918. }
  2919. try
  2920. {
  2921. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2922. using (var uploadMemoryStream = new MemoryStream())
  2923. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2924. {
  2925. sw.Write("Ann & Gert");
  2926. sw.Flush();
  2927. uploadMemoryStream.Position = 0;
  2928. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2929. client.EndUploadFile(asyncResult);
  2930. }
  2931. using (var downloadMemoryStream = new MemoryStream())
  2932. {
  2933. client.DownloadFile(remoteFile, downloadMemoryStream);
  2934. downloadMemoryStream.Position = 0;
  2935. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2936. {
  2937. var content = sr.ReadToEnd();
  2938. Assert.AreEqual("Ann & Gert", content);
  2939. }
  2940. }
  2941. }
  2942. finally
  2943. {
  2944. if (client.Exists(remoteFile))
  2945. {
  2946. client.DeleteFile(remoteFile);
  2947. }
  2948. }
  2949. }
  2950. }
  2951. [TestMethod]
  2952. public void Sftp_UploadAndDownloadBigFile()
  2953. {
  2954. const int size = 50 * 1024 * 1024;
  2955. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2956. {
  2957. client.Connect();
  2958. var remoteFile = GenerateUniqueRemoteFileName();
  2959. if (client.Exists(remoteFile))
  2960. {
  2961. client.Delete(remoteFile);
  2962. }
  2963. try
  2964. {
  2965. var memoryStream = CreateMemoryStream(size);
  2966. memoryStream.Position = 0;
  2967. client.UploadFile(memoryStream, remoteFile);
  2968. var stopwatch = new Stopwatch();
  2969. stopwatch.Start();
  2970. // check uploaded file
  2971. memoryStream = new MemoryStream();
  2972. client.DownloadFile(remoteFile, memoryStream);
  2973. Assert.AreEqual(size, memoryStream.Length);
  2974. stopwatch.Stop();
  2975. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  2976. Console.WriteLine(@"Transfer speed: {0:N2} KB/s",
  2977. CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds));
  2978. }
  2979. finally
  2980. {
  2981. if (client.Exists(remoteFile))
  2982. {
  2983. client.Delete(remoteFile);
  2984. }
  2985. }
  2986. }
  2987. }
  2988. /// <summary>
  2989. /// Issue 1672
  2990. /// </summary>
  2991. [TestMethod]
  2992. public void Sftp_CurrentWorkingDirectory()
  2993. {
  2994. const string homeDirectory = "/home/sshnet";
  2995. const string otherDirectory = homeDirectory + "/dir";
  2996. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2997. {
  2998. client.Connect();
  2999. if (client.Exists(otherDirectory))
  3000. {
  3001. client.DeleteDirectory(otherDirectory);
  3002. }
  3003. try
  3004. {
  3005. client.CreateDirectory(otherDirectory);
  3006. client.ChangeDirectory(otherDirectory);
  3007. using (var s = CreateStreamWithContent("A"))
  3008. {
  3009. client.UploadFile(s, "a.txt");
  3010. }
  3011. using (var s = new MemoryStream())
  3012. {
  3013. client.DownloadFile("a.txt", s);
  3014. s.Position = 0;
  3015. var content = Encoding.ASCII.GetString(s.ToArray());
  3016. Assert.AreEqual("A", content);
  3017. }
  3018. Assert.IsTrue(client.Exists(otherDirectory + "/a.txt"));
  3019. client.DeleteFile("a.txt");
  3020. Assert.IsFalse(client.Exists(otherDirectory + "/a.txt"));
  3021. client.DeleteDirectory(".");
  3022. Assert.IsFalse(client.Exists(otherDirectory));
  3023. }
  3024. finally
  3025. {
  3026. if (client.Exists(otherDirectory))
  3027. {
  3028. client.DeleteDirectory(otherDirectory);
  3029. }
  3030. }
  3031. }
  3032. }
  3033. [TestMethod]
  3034. public void Sftp_Exists()
  3035. {
  3036. const string remoteHome = "/home/sshnet";
  3037. #region Setup
  3038. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3039. {
  3040. client.Connect();
  3041. #region Clean-up
  3042. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3043. {
  3044. command.Execute();
  3045. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3046. }
  3047. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3048. {
  3049. command.Execute();
  3050. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3051. }
  3052. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  3053. )
  3054. {
  3055. command.Execute();
  3056. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3057. }
  3058. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3059. {
  3060. command.Execute();
  3061. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3062. }
  3063. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3064. {
  3065. command.Execute();
  3066. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3067. }
  3068. #endregion Clean-up
  3069. #region Setup
  3070. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  3071. {
  3072. command.Execute();
  3073. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3074. }
  3075. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  3076. {
  3077. command.Execute();
  3078. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3079. }
  3080. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  3081. {
  3082. command.Execute();
  3083. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3084. }
  3085. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  3086. {
  3087. command.Execute();
  3088. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3089. }
  3090. #endregion Setup
  3091. }
  3092. #endregion Setup
  3093. #region Assert
  3094. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3095. {
  3096. client.Connect();
  3097. Assert.IsFalse(client.Exists(remoteHome + "/DoesNotExist"));
  3098. Assert.IsTrue(client.Exists(remoteHome + "/file.exists"));
  3099. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.file.exists"));
  3100. Assert.IsTrue(client.Exists(remoteHome + "/directory.exists"));
  3101. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.directory.exists"));
  3102. }
  3103. #endregion Assert
  3104. #region Teardown
  3105. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3106. {
  3107. client.Connect();
  3108. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3109. {
  3110. command.Execute();
  3111. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3112. }
  3113. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3114. {
  3115. command.Execute();
  3116. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3117. }
  3118. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  3119. {
  3120. command.Execute();
  3121. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3122. }
  3123. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3124. {
  3125. command.Execute();
  3126. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3127. }
  3128. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3129. {
  3130. command.Execute();
  3131. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3132. }
  3133. }
  3134. #endregion Teardown
  3135. }
  3136. [TestMethod]
  3137. public void Sftp_ListDirectory()
  3138. {
  3139. const string remoteDirectory = "/home/sshnet/test123";
  3140. try
  3141. {
  3142. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3143. {
  3144. client.Connect();
  3145. client.RunCommand($@"rm -Rf ""{remoteDirectory}""");
  3146. client.RunCommand($@"mkdir -p ""{remoteDirectory}""");
  3147. client.RunCommand($@"mkdir -p ""{remoteDirectory}/sub""");
  3148. client.RunCommand($@"touch ""{remoteDirectory}/file1""");
  3149. client.RunCommand($@"touch ""{remoteDirectory}/file2""");
  3150. }
  3151. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3152. {
  3153. client.Connect();
  3154. client.ChangeDirectory(remoteDirectory);
  3155. var directoryContent = client.ListDirectory(".").OrderBy(p => p.Name).ToList();
  3156. Assert.AreEqual(5, directoryContent.Count);
  3157. Assert.AreEqual(".", directoryContent[0].Name);
  3158. Assert.AreEqual($"{remoteDirectory}/.", directoryContent[0].FullName);
  3159. Assert.IsTrue(directoryContent[0].IsDirectory);
  3160. Assert.AreEqual("..", directoryContent[1].Name);
  3161. Assert.AreEqual($"{remoteDirectory}/..", directoryContent[1].FullName);
  3162. Assert.IsTrue(directoryContent[1].IsDirectory);
  3163. Assert.AreEqual("file1", directoryContent[2].Name);
  3164. Assert.AreEqual($"{remoteDirectory}/file1", directoryContent[2].FullName);
  3165. Assert.IsFalse(directoryContent[2].IsDirectory);
  3166. Assert.AreEqual("file2", directoryContent[3].Name);
  3167. Assert.AreEqual($"{remoteDirectory}/file2", directoryContent[3].FullName);
  3168. Assert.IsFalse(directoryContent[3].IsDirectory);
  3169. Assert.AreEqual("sub", directoryContent[4].Name);
  3170. Assert.AreEqual($"{remoteDirectory}/sub", directoryContent[4].FullName);
  3171. Assert.IsTrue(directoryContent[4].IsDirectory);
  3172. }
  3173. }
  3174. finally
  3175. {
  3176. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3177. {
  3178. client.Connect();
  3179. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3180. {
  3181. command.Execute();
  3182. }
  3183. }
  3184. }
  3185. }
  3186. [TestMethod]
  3187. public void Sftp_ChangeDirectory_DirectoryDoesNotExist()
  3188. {
  3189. const string remoteDirectory = "/home/sshnet/test123";
  3190. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3191. {
  3192. client.Connect();
  3193. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3194. {
  3195. command.Execute();
  3196. }
  3197. }
  3198. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3199. {
  3200. client.Connect();
  3201. try
  3202. {
  3203. client.ChangeDirectory(remoteDirectory);
  3204. Assert.Fail();
  3205. }
  3206. catch (SftpPathNotFoundException)
  3207. {
  3208. }
  3209. }
  3210. }
  3211. [TestMethod]
  3212. public void Sftp_ChangeDirectory_DirectoryExists()
  3213. {
  3214. const string remoteDirectory = "/home/sshnet/test123";
  3215. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3216. {
  3217. client.Connect();
  3218. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3219. {
  3220. command.Execute();
  3221. }
  3222. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3223. {
  3224. command.Execute();
  3225. }
  3226. }
  3227. try
  3228. {
  3229. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3230. {
  3231. client.Connect();
  3232. client.ChangeDirectory(remoteDirectory);
  3233. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3234. using (var uploadStream = CreateMemoryStream(100))
  3235. {
  3236. uploadStream.Position = 0;
  3237. client.UploadFile(uploadStream, "gert.txt");
  3238. uploadStream.Position = 0;
  3239. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3240. {
  3241. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3242. }
  3243. }
  3244. }
  3245. }
  3246. finally
  3247. {
  3248. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3249. {
  3250. client.Connect();
  3251. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3252. {
  3253. command.Execute();
  3254. }
  3255. }
  3256. }
  3257. }
  3258. [TestMethod]
  3259. public void Sftp_DownloadFile_MemoryStream()
  3260. {
  3261. const int fileSize = 500 * 1024;
  3262. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3263. {
  3264. client.Connect();
  3265. var remoteFile = GenerateUniqueRemoteFileName();
  3266. SftpCreateRemoteFile(client, remoteFile, fileSize);
  3267. try
  3268. {
  3269. using (var memoryStream = new MemoryStream())
  3270. {
  3271. var stopwatch = new Stopwatch();
  3272. stopwatch.Start();
  3273. client.DownloadFile(remoteFile, memoryStream);
  3274. stopwatch.Stop();
  3275. var transferSpeed = CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds);
  3276. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  3277. Console.WriteLine(@"Transfer speed: {0:N2} KB/s", transferSpeed);
  3278. Assert.AreEqual(fileSize, memoryStream.Length);
  3279. }
  3280. }
  3281. finally
  3282. {
  3283. if (client.Exists(remoteFile))
  3284. {
  3285. client.DeleteFile(remoteFile);
  3286. }
  3287. }
  3288. }
  3289. }
  3290. [TestMethod]
  3291. public void Sftp_SubsystemExecution_Failed()
  3292. {
  3293. var remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  3294. // Disable SFTP subsystem
  3295. remoteSshdConfig.ClearSubsystems()
  3296. .Update()
  3297. .Restart();
  3298. var remoteSshdReconfiguredToDefaultState = false;
  3299. try
  3300. {
  3301. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3302. {
  3303. try
  3304. {
  3305. client.Connect();
  3306. Assert.Fail("Establishing SFTP connection should have failed.");
  3307. }
  3308. catch (SshException ex)
  3309. {
  3310. Assert.IsNull(ex.InnerException);
  3311. Assert.AreEqual("Subsystem 'sftp' could not be executed.", ex.Message);
  3312. }
  3313. // Re-enable SFTP subsystem
  3314. remoteSshdConfig.Reset();
  3315. remoteSshdReconfiguredToDefaultState = true;
  3316. // ensure we can reconnect the same SftpClient instance
  3317. client.Connect();
  3318. // ensure SFTP session is correctly established
  3319. Assert.IsTrue(client.Exists("."));
  3320. }
  3321. }
  3322. finally
  3323. {
  3324. if (!remoteSshdReconfiguredToDefaultState)
  3325. {
  3326. remoteSshdConfig.Reset();
  3327. }
  3328. }
  3329. }
  3330. [TestMethod]
  3331. public void Sftp_SftpFileStream_ReadAndWrite()
  3332. {
  3333. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3334. {
  3335. client.Connect();
  3336. var remoteFile = GenerateUniqueRemoteFileName();
  3337. if (client.Exists(remoteFile))
  3338. {
  3339. client.DeleteFile(remoteFile);
  3340. }
  3341. try
  3342. {
  3343. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3344. {
  3345. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3346. }
  3347. // switch from read to write mode
  3348. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3349. {
  3350. Assert.AreEqual(4, s.ReadByte());
  3351. Assert.AreEqual(3, s.ReadByte());
  3352. Assert.AreEqual(2, s.Position);
  3353. s.WriteByte(7);
  3354. s.Write(new byte[] { 8, 9, 10, 11, 12 }, 1, 3);
  3355. Assert.AreEqual(6, s.Position);
  3356. }
  3357. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3358. {
  3359. Assert.AreEqual(6, s.Length);
  3360. var buffer = new byte[s.Length];
  3361. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3362. CollectionAssert.AreEqual(new byte[] { 4, 3, 7, 9, 10, 11 }, buffer);
  3363. // Ensure we've reached end of the stream
  3364. Assert.AreEqual(-1, s.ReadByte());
  3365. }
  3366. // switch from read to write mode, and back to read mode and finally
  3367. // append a byte
  3368. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3369. {
  3370. Assert.AreEqual(4, s.ReadByte());
  3371. Assert.AreEqual(3, s.ReadByte());
  3372. Assert.AreEqual(7, s.ReadByte());
  3373. s.Write(new byte[] { 0, 1, 6, 4 }, 1, 2);
  3374. Assert.AreEqual(11, s.ReadByte());
  3375. // Ensure we've reached end of the stream
  3376. Assert.AreEqual(-1, s.ReadByte());
  3377. s.WriteByte(12);
  3378. }
  3379. // switch from write to read mode, and back to write mode
  3380. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3381. {
  3382. s.WriteByte(5);
  3383. Assert.AreEqual(3, s.ReadByte());
  3384. s.WriteByte(13);
  3385. Assert.AreEqual(3, s.Position);
  3386. }
  3387. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3388. {
  3389. Assert.AreEqual(7, s.Length);
  3390. var buffer = new byte[s.Length];
  3391. Assert.AreEqual(7, s.Read(buffer, offset: 0, buffer.Length));
  3392. CollectionAssert.AreEqual(new byte[] { 5, 3, 13, 1, 6, 11, 12 }, buffer);
  3393. // Ensure we've reached end of the stream
  3394. Assert.AreEqual(-1, s.ReadByte());
  3395. }
  3396. }
  3397. finally
  3398. {
  3399. if (client.Exists(remoteFile))
  3400. {
  3401. client.DeleteFile(remoteFile);
  3402. }
  3403. }
  3404. }
  3405. }
  3406. [TestMethod]
  3407. public void Sftp_SftpFileStream_SetLength_ReduceLength()
  3408. {
  3409. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3410. {
  3411. client.Connect();
  3412. var remoteFile = GenerateUniqueRemoteFileName();
  3413. if (client.Exists(remoteFile))
  3414. {
  3415. client.DeleteFile(remoteFile);
  3416. }
  3417. try
  3418. {
  3419. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3420. {
  3421. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3422. }
  3423. // reduce length while in write mode, with data in write buffer, and before
  3424. // current position
  3425. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  3426. {
  3427. s.Position = 3;
  3428. s.Write(new byte[] { 6, 7, 8, 9 }, offset: 0, count: 4);
  3429. Assert.AreEqual(7, s.Position);
  3430. // verify buffer has not yet been flushed
  3431. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3432. {
  3433. Assert.AreEqual(4, fs.ReadByte());
  3434. Assert.AreEqual(3, fs.ReadByte());
  3435. Assert.AreEqual(2, fs.ReadByte());
  3436. // Ensure we've reached end of the stream
  3437. Assert.AreEqual(-1, fs.ReadByte());
  3438. }
  3439. s.SetLength(5);
  3440. Assert.AreEqual(5, s.Position);
  3441. // verify that buffer was flushed and size has been modified
  3442. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3443. {
  3444. Assert.AreEqual(4, fs.ReadByte());
  3445. Assert.AreEqual(3, fs.ReadByte());
  3446. Assert.AreEqual(2, fs.ReadByte());
  3447. Assert.AreEqual(6, fs.ReadByte());
  3448. Assert.AreEqual(7, fs.ReadByte());
  3449. // Ensure we've reached end of the stream
  3450. Assert.AreEqual(-1, fs.ReadByte());
  3451. }
  3452. s.WriteByte(1);
  3453. }
  3454. // verify that last byte was correctly written to the file
  3455. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3456. {
  3457. Assert.AreEqual(6, s.Length);
  3458. var buffer = new byte[s.Length + 2];
  3459. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3460. CollectionAssert.AreEqual(new byte[] { 4, 3, 2, 6, 7, 1, 0, 0 }, buffer);
  3461. // Ensure we've reached end of the stream
  3462. Assert.AreEqual(-1, s.ReadByte());
  3463. }
  3464. // reduce length while in read mode, but beyond current position
  3465. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3466. {
  3467. var buffer = new byte[1];
  3468. Assert.AreEqual(1, s.Read(buffer, offset: 0, buffer.Length));
  3469. CollectionAssert.AreEqual(new byte[] { 4 }, buffer);
  3470. s.SetLength(3);
  3471. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  3472. {
  3473. w.Write(new byte[] { 8, 1, 6, 2 }, offset: 0, count: 4);
  3474. }
  3475. // verify that position was not changed
  3476. Assert.AreEqual(1, s.Position);
  3477. // verify that read buffer was cleared
  3478. Assert.AreEqual(1, s.ReadByte());
  3479. Assert.AreEqual(6, s.ReadByte());
  3480. Assert.AreEqual(2, s.ReadByte());
  3481. // Ensure we've reached end of the stream
  3482. Assert.AreEqual(-1, s.ReadByte());
  3483. Assert.AreEqual(4, s.Length);
  3484. }
  3485. // reduce length while in read mode, but before current position
  3486. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3487. {
  3488. var buffer = new byte[4];
  3489. Assert.AreEqual(4, s.Read(buffer, offset: 0, buffer.Length));
  3490. CollectionAssert.AreEqual(new byte[] { 8, 1, 6, 2 }, buffer);
  3491. Assert.AreEqual(4, s.Position);
  3492. s.SetLength(3);
  3493. // verify that position was moved to last byte
  3494. Assert.AreEqual(3, s.Position);
  3495. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3496. {
  3497. Assert.AreEqual(3, w.Length);
  3498. Assert.AreEqual(8, w.ReadByte());
  3499. Assert.AreEqual(1, w.ReadByte());
  3500. Assert.AreEqual(6, w.ReadByte());
  3501. // Ensure we've reached end of the stream
  3502. Assert.AreEqual(-1, w.ReadByte());
  3503. }
  3504. // Ensure we've reached end of the stream
  3505. Assert.AreEqual(-1, s.ReadByte());
  3506. }
  3507. }
  3508. finally
  3509. {
  3510. if (client.Exists(remoteFile))
  3511. {
  3512. client.DeleteFile(remoteFile);
  3513. }
  3514. }
  3515. }
  3516. }
  3517. [TestMethod]
  3518. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginBegin()
  3519. {
  3520. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3521. {
  3522. client.BufferSize = 500;
  3523. client.Connect();
  3524. var remoteFile = GenerateUniqueRemoteFileName();
  3525. if (client.Exists(remoteFile))
  3526. {
  3527. client.DeleteFile(remoteFile);
  3528. }
  3529. try
  3530. {
  3531. // create single-byte file
  3532. using (var fs = client.OpenWrite(remoteFile))
  3533. {
  3534. fs.WriteByte(0x04);
  3535. }
  3536. // seek beyond EOF but not beyond buffer size
  3537. // do not write anything
  3538. using (var fs = client.OpenWrite(remoteFile))
  3539. {
  3540. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3541. Assert.AreEqual(3, newPosition);
  3542. Assert.AreEqual(3, fs.Position);
  3543. }
  3544. using (var fs = client.OpenRead(remoteFile))
  3545. {
  3546. Assert.AreEqual(1, fs.Length);
  3547. Assert.AreEqual(0x04, fs.ReadByte());
  3548. // Ensure we've reached end of the stream
  3549. Assert.AreEqual(-1, fs.ReadByte());
  3550. }
  3551. client.DeleteFile(remoteFile);
  3552. // create single-byte file
  3553. using (var fs = client.OpenWrite(remoteFile))
  3554. {
  3555. fs.WriteByte(0x04);
  3556. }
  3557. // seek beyond EOF and beyond buffer size
  3558. // do not write anything
  3559. using (var fs = client.OpenWrite(remoteFile))
  3560. {
  3561. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  3562. Assert.AreEqual(700, newPosition);
  3563. Assert.AreEqual(700, fs.Position);
  3564. }
  3565. using (var fs = client.OpenRead(remoteFile))
  3566. {
  3567. Assert.AreEqual(1, fs.Length);
  3568. Assert.AreEqual(0x04, fs.ReadByte());
  3569. // Ensure we've reached end of the stream
  3570. Assert.AreEqual(-1, fs.ReadByte());
  3571. }
  3572. client.DeleteFile(remoteFile);
  3573. // create single-byte file
  3574. using (var fs = client.OpenWrite(remoteFile))
  3575. {
  3576. fs.WriteByte(0x04);
  3577. }
  3578. // seek beyond EOF but not beyond buffer size
  3579. // write less bytes than buffer size
  3580. var seekOffset = 3L;
  3581. // buffer holding the data that we'll write to the file
  3582. var writeBuffer = GenerateRandom(size: 7);
  3583. using (var fs = client.OpenWrite(remoteFile))
  3584. {
  3585. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3586. Assert.AreEqual(seekOffset, newPosition);
  3587. Assert.AreEqual(seekOffset, fs.Position);
  3588. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3589. }
  3590. using (var fs = client.OpenRead(remoteFile))
  3591. {
  3592. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3593. Assert.AreEqual(0x04, fs.ReadByte());
  3594. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  3595. Assert.AreEqual(soughtOverReadBufferffer.Length, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  3596. Assert.IsTrue(new byte[soughtOverReadBufferffer.Length].IsEqualTo(soughtOverReadBufferffer));
  3597. var readBuffer = new byte[writeBuffer.Length];
  3598. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3599. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3600. // Ensure we've reached end of the stream
  3601. Assert.AreEqual(-1, fs.ReadByte());
  3602. }
  3603. client.DeleteFile(remoteFile);
  3604. // create single-byte file
  3605. using (var fs = client.OpenWrite(remoteFile))
  3606. {
  3607. fs.WriteByte(0x04);
  3608. }
  3609. // seek beyond EOF and beyond buffer size
  3610. // write less bytes than buffer size
  3611. seekOffset = 700L;
  3612. // buffer holding the data that we'll write to the file
  3613. writeBuffer = GenerateRandom(size: 4);
  3614. using (var fs = client.OpenWrite(remoteFile))
  3615. {
  3616. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3617. Assert.AreEqual(seekOffset, newPosition);
  3618. Assert.AreEqual(seekOffset, fs.Position);
  3619. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3620. }
  3621. using (var fs = client.OpenRead(remoteFile))
  3622. {
  3623. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3624. Assert.AreEqual(0x04, fs.ReadByte());
  3625. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  3626. Assert.AreEqual(soughtOverReadBufferffer.Length, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  3627. Assert.IsTrue(new byte[soughtOverReadBufferffer.Length].IsEqualTo(soughtOverReadBufferffer));
  3628. var readBuffer = new byte[writeBuffer.Length];
  3629. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3630. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3631. // Ensure we've reached end of the stream
  3632. Assert.AreEqual(-1, fs.ReadByte());
  3633. }
  3634. client.DeleteFile(remoteFile);
  3635. // create single-byte file
  3636. using (var fs = client.OpenWrite(remoteFile))
  3637. {
  3638. fs.WriteByte(0x04);
  3639. }
  3640. // seek beyond EOF but not beyond buffer size
  3641. // write more bytes than buffer size
  3642. writeBuffer = GenerateRandom(size: 600);
  3643. using (var fs = client.OpenWrite(remoteFile))
  3644. {
  3645. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3646. Assert.AreEqual(3, newPosition);
  3647. Assert.AreEqual(3, fs.Position);
  3648. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3649. }
  3650. using (var fs = client.OpenRead(remoteFile))
  3651. {
  3652. Assert.AreEqual(3 + writeBuffer.Length, fs.Length);
  3653. Assert.AreEqual(0x04, fs.ReadByte());
  3654. Assert.AreEqual(0x00, fs.ReadByte());
  3655. Assert.AreEqual(0x00, fs.ReadByte());
  3656. var readBuffer = new byte[writeBuffer.Length];
  3657. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3658. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3659. // Ensure we've reached end of the stream
  3660. Assert.AreEqual(-1, fs.ReadByte());
  3661. }
  3662. client.DeleteFile(remoteFile);
  3663. // create single-byte file
  3664. using (var fs = client.OpenWrite(remoteFile))
  3665. {
  3666. fs.WriteByte(0x04);
  3667. }
  3668. // seek beyond EOF and beyond buffer size
  3669. // write more bytes than buffer size
  3670. writeBuffer = GenerateRandom(size: 600);
  3671. using (var fs = client.OpenWrite(remoteFile))
  3672. {
  3673. var newPosition = fs.Seek(offset: 550, SeekOrigin.Begin);
  3674. Assert.AreEqual(550, newPosition);
  3675. Assert.AreEqual(550, fs.Position);
  3676. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3677. }
  3678. using (var fs = client.OpenRead(remoteFile))
  3679. {
  3680. Assert.AreEqual(550 + writeBuffer.Length, fs.Length);
  3681. Assert.AreEqual(0x04, fs.ReadByte());
  3682. var soughtOverReadBuffer = new byte[550 - 1];
  3683. Assert.AreEqual(550 - 1, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3684. Assert.IsTrue(new byte[550 - 1].IsEqualTo(soughtOverReadBuffer));
  3685. var readBuffer = new byte[writeBuffer.Length];
  3686. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3687. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3688. // Ensure we've reached end of the stream
  3689. Assert.AreEqual(-1, fs.ReadByte());
  3690. }
  3691. }
  3692. finally
  3693. {
  3694. if (client.Exists(remoteFile))
  3695. {
  3696. client.DeleteFile(remoteFile);
  3697. }
  3698. }
  3699. }
  3700. }
  3701. [TestMethod]
  3702. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginEnd()
  3703. {
  3704. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3705. {
  3706. client.BufferSize = 500;
  3707. client.Connect();
  3708. var remoteFile = GenerateUniqueRemoteFileName();
  3709. if (client.Exists(remoteFile))
  3710. {
  3711. client.DeleteFile(remoteFile);
  3712. }
  3713. try
  3714. {
  3715. // create single-byte file
  3716. using (var fs = client.OpenWrite(remoteFile))
  3717. {
  3718. fs.WriteByte(0x04);
  3719. }
  3720. // seek beyond EOF but not beyond buffer size
  3721. // do not write anything
  3722. using (var fs = client.OpenWrite(remoteFile))
  3723. {
  3724. var newPosition = fs.Seek(offset: 3L, SeekOrigin.End);
  3725. Assert.AreEqual(4, newPosition);
  3726. Assert.AreEqual(4, fs.Position);
  3727. }
  3728. using (var fs = client.OpenRead(remoteFile))
  3729. {
  3730. Assert.AreEqual(1, fs.Length);
  3731. Assert.AreEqual(0x04, fs.ReadByte());
  3732. // Ensure we've reached end of the stream
  3733. Assert.AreEqual(-1, fs.ReadByte());
  3734. }
  3735. client.DeleteFile(remoteFile);
  3736. // create single-byte file
  3737. using (var fs = client.OpenWrite(remoteFile))
  3738. {
  3739. fs.WriteByte(0x04);
  3740. }
  3741. // seek beyond EOF and beyond buffer size
  3742. // do not write anything
  3743. using (var fs = client.OpenWrite(remoteFile))
  3744. {
  3745. var newPosition = fs.Seek(offset: 700L, SeekOrigin.End);
  3746. Assert.AreEqual(701, newPosition);
  3747. Assert.AreEqual(701, fs.Position);
  3748. }
  3749. using (var fs = client.OpenRead(remoteFile))
  3750. {
  3751. Assert.AreEqual(1, fs.Length);
  3752. Assert.AreEqual(0x04, fs.ReadByte());
  3753. // Ensure we've reached end of the stream
  3754. Assert.AreEqual(-1, fs.ReadByte());
  3755. }
  3756. client.DeleteFile(remoteFile);
  3757. // create single-byte file
  3758. using (var fs = client.OpenWrite(remoteFile))
  3759. {
  3760. fs.WriteByte(0x04);
  3761. }
  3762. // seek beyond EOF but not beyond buffer size
  3763. // write less bytes than buffer size
  3764. var seekOffset = 3L;
  3765. // buffer holding the data that we'll write to the file
  3766. var writeBuffer = GenerateRandom(size: 7);
  3767. using (var fs = client.OpenWrite(remoteFile))
  3768. {
  3769. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3770. Assert.AreEqual(4, newPosition);
  3771. Assert.AreEqual(4, fs.Position);
  3772. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3773. }
  3774. using (var fs = client.OpenRead(remoteFile))
  3775. {
  3776. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3777. Assert.AreEqual(0x04, fs.ReadByte());
  3778. var soughtOverReadBuffer = new byte[seekOffset];
  3779. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3780. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3781. var readBuffer = new byte[writeBuffer.Length];
  3782. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3783. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3784. // Ensure we've reached end of the stream
  3785. Assert.AreEqual(-1, fs.ReadByte());
  3786. }
  3787. client.DeleteFile(remoteFile);
  3788. // create single-byte file
  3789. using (var fs = client.OpenWrite(remoteFile))
  3790. {
  3791. fs.WriteByte(0x04);
  3792. }
  3793. // seek beyond EOF and beyond buffer size
  3794. // write less bytes than buffer size
  3795. seekOffset = 700L;
  3796. // buffer holding the data that we'll write to the file
  3797. writeBuffer = GenerateRandom(size: 4);
  3798. using (var fs = client.OpenWrite(remoteFile))
  3799. {
  3800. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3801. Assert.AreEqual(1 + seekOffset, newPosition);
  3802. Assert.AreEqual(1 + seekOffset, fs.Position);
  3803. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3804. }
  3805. using (var fs = client.OpenRead(remoteFile))
  3806. {
  3807. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3808. Assert.AreEqual(0x04, fs.ReadByte());
  3809. var soughtOverReadBuffer = new byte[seekOffset];
  3810. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3811. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3812. var readBuffer = new byte[writeBuffer.Length];
  3813. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3814. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3815. // Ensure we've reached end of the stream
  3816. Assert.AreEqual(-1, fs.ReadByte());
  3817. }
  3818. client.DeleteFile(remoteFile);
  3819. // create single-byte file
  3820. using (var fs = client.OpenWrite(remoteFile))
  3821. {
  3822. fs.WriteByte(0x04);
  3823. }
  3824. // seek beyond EOF but not beyond buffer size
  3825. // write more bytes than buffer size
  3826. seekOffset = 3L;
  3827. writeBuffer = GenerateRandom(size: 600);
  3828. using (var fs = client.OpenWrite(remoteFile))
  3829. {
  3830. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3831. Assert.AreEqual(1 + seekOffset, newPosition);
  3832. Assert.AreEqual(1 + seekOffset, fs.Position);
  3833. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3834. }
  3835. using (var fs = client.OpenRead(remoteFile))
  3836. {
  3837. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3838. Assert.AreEqual(0x04, fs.ReadByte());
  3839. var soughtOverReadBuffer = new byte[seekOffset];
  3840. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3841. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3842. var readBuffer = new byte[writeBuffer.Length];
  3843. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3844. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3845. // Ensure we've reached end of the stream
  3846. Assert.AreEqual(-1, fs.ReadByte());
  3847. }
  3848. client.DeleteFile(remoteFile);
  3849. // create single-byte file
  3850. using (var fs = client.OpenWrite(remoteFile))
  3851. {
  3852. fs.WriteByte(0x04);
  3853. }
  3854. // seek beyond EOF and beyond buffer size
  3855. // write more bytes than buffer size
  3856. seekOffset = 550L;
  3857. writeBuffer = GenerateRandom(size: 600);
  3858. using (var fs = client.OpenWrite(remoteFile))
  3859. {
  3860. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3861. Assert.AreEqual(1 + seekOffset, newPosition);
  3862. Assert.AreEqual(1 + seekOffset, fs.Position);
  3863. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3864. }
  3865. using (var fs = client.OpenRead(remoteFile))
  3866. {
  3867. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3868. Assert.AreEqual(0x04, fs.ReadByte());
  3869. var soughtOverReadBuffer = new byte[seekOffset];
  3870. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3871. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3872. var readBuffer = new byte[writeBuffer.Length];
  3873. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3874. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3875. // Ensure we've reached end of the stream
  3876. Assert.AreEqual(-1, fs.ReadByte());
  3877. }
  3878. }
  3879. finally
  3880. {
  3881. if (client.Exists(remoteFile))
  3882. {
  3883. client.DeleteFile(remoteFile);
  3884. }
  3885. }
  3886. }
  3887. }
  3888. [TestMethod]
  3889. public void Sftp_SftpFileStream_Seek_NegativeOffSet_SeekOriginEnd()
  3890. {
  3891. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3892. {
  3893. client.BufferSize = 500;
  3894. client.Connect();
  3895. var remoteFile = GenerateUniqueRemoteFileName();
  3896. if (client.Exists(remoteFile))
  3897. {
  3898. client.DeleteFile(remoteFile);
  3899. }
  3900. try
  3901. {
  3902. using (var fs = client.OpenWrite(remoteFile))
  3903. {
  3904. fs.WriteByte(0x04);
  3905. fs.WriteByte(0x07);
  3906. fs.WriteByte(0x05);
  3907. }
  3908. // seek within file and not beyond buffer size
  3909. // do not write anything
  3910. using (var fs = client.OpenWrite(remoteFile))
  3911. {
  3912. var newPosition = fs.Seek(offset: -2L, SeekOrigin.End);
  3913. Assert.AreEqual(1, newPosition);
  3914. Assert.AreEqual(1, fs.Position);
  3915. }
  3916. using (var fs = client.OpenRead(remoteFile))
  3917. {
  3918. Assert.AreEqual(3, fs.Length);
  3919. Assert.AreEqual(0x04, fs.ReadByte());
  3920. Assert.AreEqual(0x07, fs.ReadByte());
  3921. Assert.AreEqual(0x05, fs.ReadByte());
  3922. // Ensure we've reached end of the stream
  3923. Assert.AreEqual(-1, fs.ReadByte());
  3924. }
  3925. client.DeleteFile(remoteFile);
  3926. // buffer holding the data that we'll write to the file
  3927. var writeBuffer = GenerateRandom(size: (int) client.BufferSize + 200);
  3928. using (var fs = client.OpenWrite(remoteFile))
  3929. {
  3930. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3931. }
  3932. // seek within EOF and beyond buffer size
  3933. // do not write anything
  3934. using (var fs = client.OpenWrite(remoteFile))
  3935. {
  3936. var newPosition = fs.Seek(offset: -100L, SeekOrigin.End);
  3937. Assert.AreEqual(600, newPosition);
  3938. Assert.AreEqual(600, fs.Position);
  3939. }
  3940. using (var fs = client.OpenRead(remoteFile))
  3941. {
  3942. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3943. var readBuffer = new byte[writeBuffer.Length];
  3944. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3945. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3946. // Ensure we've reached end of the stream
  3947. Assert.AreEqual(-1, fs.ReadByte());
  3948. }
  3949. client.DeleteFile(remoteFile);
  3950. // seek within EOF and within buffer size
  3951. // write less bytes than buffer size
  3952. using (var fs = client.OpenWrite(remoteFile))
  3953. {
  3954. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3955. var newPosition = fs.Seek(offset: -3, SeekOrigin.End);
  3956. Assert.AreEqual(697, newPosition);
  3957. Assert.AreEqual(697, fs.Position);
  3958. fs.WriteByte(0x01);
  3959. fs.WriteByte(0x05);
  3960. fs.WriteByte(0x04);
  3961. fs.WriteByte(0x07);
  3962. }
  3963. using (var fs = client.OpenRead(remoteFile))
  3964. {
  3965. Assert.AreEqual(writeBuffer.Length + 1, fs.Length);
  3966. var readBuffer = new byte[writeBuffer.Length - 3];
  3967. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3968. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  3969. Assert.AreEqual(0x01, fs.ReadByte());
  3970. Assert.AreEqual(0x05, fs.ReadByte());
  3971. Assert.AreEqual(0x04, fs.ReadByte());
  3972. Assert.AreEqual(0x07, fs.ReadByte());
  3973. // Ensure we've reached end of the stream
  3974. Assert.AreEqual(-1, fs.ReadByte());
  3975. }
  3976. client.DeleteFile(remoteFile);
  3977. // buffer holding the data that we'll write to the file
  3978. writeBuffer = GenerateRandom(size: (int) client.BufferSize * 4);
  3979. // seek within EOF and beyond buffer size
  3980. // write less bytes than buffer size
  3981. using (var fs = client.OpenWrite(remoteFile))
  3982. {
  3983. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3984. var newPosition = fs.Seek(offset: -(client.BufferSize * 2), SeekOrigin.End);
  3985. Assert.AreEqual(1000, newPosition);
  3986. Assert.AreEqual(1000, fs.Position);
  3987. fs.WriteByte(0x01);
  3988. fs.WriteByte(0x05);
  3989. fs.WriteByte(0x04);
  3990. fs.WriteByte(0x07);
  3991. }
  3992. using (var fs = client.OpenRead(remoteFile))
  3993. {
  3994. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3995. // First part of file should not have been touched
  3996. var readBuffer = new byte[(int) client.BufferSize * 2];
  3997. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3998. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  3999. // Check part that should have been updated
  4000. Assert.AreEqual(0x01, fs.ReadByte());
  4001. Assert.AreEqual(0x05, fs.ReadByte());
  4002. Assert.AreEqual(0x04, fs.ReadByte());
  4003. Assert.AreEqual(0x07, fs.ReadByte());
  4004. // Remaining bytes should not have been touched
  4005. readBuffer = new byte[((int) client.BufferSize * 2) - 4];
  4006. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4007. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Skip(((int)client.BufferSize * 2) + 4).Take(readBuffer.Length)));
  4008. // Ensure we've reached end of the stream
  4009. Assert.AreEqual(-1, fs.ReadByte());
  4010. }
  4011. }
  4012. finally
  4013. {
  4014. if (client.Exists(remoteFile))
  4015. {
  4016. client.DeleteFile(remoteFile);
  4017. }
  4018. }
  4019. }
  4020. }
  4021. /// https://github.com/sshnet/SSH.NET/issues/253
  4022. [TestMethod]
  4023. public void Sftp_SftpFileStream_Seek_Issue253()
  4024. {
  4025. var buf = Encoding.UTF8.GetBytes("123456");
  4026. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4027. {
  4028. client.Connect();
  4029. var remoteFile = GenerateUniqueRemoteFileName();
  4030. if (client.Exists(remoteFile))
  4031. {
  4032. client.DeleteFile(remoteFile);
  4033. }
  4034. try
  4035. {
  4036. using (var ws = client.OpenWrite(remoteFile))
  4037. {
  4038. ws.Write(buf, offset: 0, count: 3);
  4039. }
  4040. using (var ws = client.OpenWrite(remoteFile))
  4041. {
  4042. var newPosition = ws.Seek(offset: 3, SeekOrigin.Begin);
  4043. Assert.AreEqual(3, newPosition);
  4044. Assert.AreEqual(3, ws.Position);
  4045. ws.Write(buf, 3, 3);
  4046. }
  4047. var actual = client.ReadAllText(remoteFile, Encoding.UTF8);
  4048. Assert.AreEqual("123456", actual);
  4049. }
  4050. finally
  4051. {
  4052. if (client.Exists(remoteFile))
  4053. {
  4054. client.DeleteFile(remoteFile);
  4055. }
  4056. }
  4057. }
  4058. }
  4059. [TestMethod]
  4060. public void Sftp_SftpFileStream_Seek_WithinReadBuffer()
  4061. {
  4062. var originalContent = GenerateRandom(size: 800);
  4063. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4064. {
  4065. client.BufferSize = 500;
  4066. client.Connect();
  4067. var remoteFile = GenerateUniqueRemoteFileName();
  4068. if (client.Exists(remoteFile))
  4069. {
  4070. client.DeleteFile(remoteFile);
  4071. }
  4072. try
  4073. {
  4074. using (var fs = client.OpenWrite(remoteFile))
  4075. {
  4076. fs.Write(originalContent, offset: 0, originalContent.Length);
  4077. }
  4078. using (var fs = client.OpenRead(remoteFile))
  4079. {
  4080. var readBuffer = new byte[200];
  4081. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4082. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  4083. Assert.AreEqual(3L, newPosition);
  4084. Assert.AreEqual(3L, fs.Position);
  4085. }
  4086. client.DeleteFile(remoteFile);
  4087. #region Seek beyond EOF and beyond buffer size do not write anything
  4088. // create single-byte file
  4089. using (var fs = client.OpenWrite(remoteFile))
  4090. {
  4091. fs.WriteByte(0x04);
  4092. }
  4093. using (var fs = client.OpenRead(remoteFile))
  4094. {
  4095. Assert.AreEqual(1, fs.Length);
  4096. Assert.AreEqual(0x04, fs.ReadByte());
  4097. // Ensure we've reached end of the stream
  4098. Assert.AreEqual(-1, fs.ReadByte());
  4099. }
  4100. using (var fs = client.OpenWrite(remoteFile))
  4101. {
  4102. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  4103. Assert.AreEqual(700L, newPosition);
  4104. Assert.AreEqual(700L, fs.Position);
  4105. }
  4106. using (var fs = client.OpenRead(remoteFile))
  4107. {
  4108. Assert.AreEqual(1, fs.Length);
  4109. Assert.AreEqual(0x04, fs.ReadByte());
  4110. // Ensure we've reached end of the stream
  4111. Assert.AreEqual(-1, fs.ReadByte());
  4112. }
  4113. client.DeleteFile(remoteFile);
  4114. #endregion Seek beyond EOF and beyond buffer size do not write anything
  4115. #region Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4116. // create single-byte file
  4117. using (var fs = client.OpenWrite(remoteFile))
  4118. {
  4119. fs.WriteByte(0x04);
  4120. }
  4121. var seekOffset = 3L;
  4122. var writeBuffer = GenerateRandom(size: 7);
  4123. using (var fs = client.OpenWrite(remoteFile))
  4124. {
  4125. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4126. Assert.AreEqual(seekOffset, newPosition);
  4127. Assert.AreEqual(seekOffset, fs.Position);
  4128. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4129. }
  4130. using (var fs = client.OpenRead(remoteFile))
  4131. {
  4132. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4133. Assert.AreEqual(0x04, fs.ReadByte());
  4134. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4135. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4136. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4137. var readBuffer = new byte[writeBuffer.Length];
  4138. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4139. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4140. // Ensure we've reached end of the stream
  4141. Assert.AreEqual(-1, fs.ReadByte());
  4142. }
  4143. client.DeleteFile(remoteFile);
  4144. #endregion Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4145. #region Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4146. // create single-byte file
  4147. using (var fs = client.OpenWrite(remoteFile))
  4148. {
  4149. fs.WriteByte(0x04);
  4150. }
  4151. seekOffset = 700L;
  4152. writeBuffer = GenerateRandom(size: 4);
  4153. using (var fs = client.OpenWrite(remoteFile))
  4154. {
  4155. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4156. Assert.AreEqual(seekOffset, newPosition);
  4157. Assert.AreEqual(seekOffset, fs.Position);
  4158. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4159. }
  4160. using (var fs = client.OpenRead(remoteFile))
  4161. {
  4162. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4163. Assert.AreEqual(0x04, fs.ReadByte());
  4164. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  4165. Assert.AreEqual(soughtOverReadBufferffer.Length, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  4166. Assert.IsTrue(new byte[soughtOverReadBufferffer.Length].IsEqualTo(soughtOverReadBufferffer));
  4167. var readBuffer = new byte[writeBuffer.Length];
  4168. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4169. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4170. // Ensure we've reached end of the stream
  4171. Assert.AreEqual(-1, fs.ReadByte());
  4172. }
  4173. client.DeleteFile(remoteFile);
  4174. #endregion Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4175. #region Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4176. // create single-byte file
  4177. using (var fs = client.OpenWrite(remoteFile))
  4178. {
  4179. fs.WriteByte(0x04);
  4180. }
  4181. seekOffset = 3L;
  4182. writeBuffer = GenerateRandom(size: 600);
  4183. using (var fs = client.OpenWrite(remoteFile))
  4184. {
  4185. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4186. Assert.AreEqual(seekOffset, newPosition);
  4187. Assert.AreEqual(seekOffset, fs.Position);
  4188. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4189. }
  4190. using (var fs = client.OpenRead(remoteFile))
  4191. {
  4192. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4193. Assert.AreEqual(0x04, fs.ReadByte());
  4194. Assert.AreEqual(0x00, fs.ReadByte());
  4195. Assert.AreEqual(0x00, fs.ReadByte());
  4196. var readBuffer = new byte[writeBuffer.Length];
  4197. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4198. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4199. // Ensure we've reached end of the stream
  4200. Assert.AreEqual(-1, fs.ReadByte());
  4201. }
  4202. client.DeleteFile(remoteFile);
  4203. #endregion Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4204. #region Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4205. // create single-byte file
  4206. using (var fs = client.OpenWrite(remoteFile))
  4207. {
  4208. fs.WriteByte(0x04);
  4209. }
  4210. seekOffset = 550L;
  4211. writeBuffer = GenerateRandom(size: 600);
  4212. using (var fs = client.OpenWrite(remoteFile))
  4213. {
  4214. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4215. Assert.AreEqual(seekOffset, newPosition);
  4216. Assert.AreEqual(seekOffset, fs.Position);
  4217. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4218. }
  4219. using (var fs = client.OpenRead(remoteFile))
  4220. {
  4221. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4222. Assert.AreEqual(0x04, fs.ReadByte());
  4223. var soughtOverReadBufferffer = new byte[seekOffset - 1];
  4224. Assert.AreEqual(seekOffset - 1, fs.Read(soughtOverReadBufferffer, offset: 0, soughtOverReadBufferffer.Length));
  4225. Assert.IsTrue(new byte[seekOffset - 1].IsEqualTo(soughtOverReadBufferffer));
  4226. var readBuffer = new byte[writeBuffer.Length];
  4227. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4228. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4229. // Ensure we've reached end of the stream
  4230. Assert.AreEqual(-1, fs.ReadByte());
  4231. }
  4232. client.DeleteFile(remoteFile);
  4233. #endregion Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4234. }
  4235. finally
  4236. {
  4237. if (client.Exists(remoteFile))
  4238. {
  4239. client.DeleteFile(remoteFile);
  4240. }
  4241. }
  4242. }
  4243. }
  4244. [TestMethod]
  4245. public void Sftp_SftpFileStream_SetLength_FileDoesNotExist()
  4246. {
  4247. var size = new Random().Next(500, 5000);
  4248. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4249. {
  4250. client.Connect();
  4251. var remoteFile = GenerateUniqueRemoteFileName();
  4252. if (client.Exists(remoteFile))
  4253. {
  4254. client.DeleteFile(remoteFile);
  4255. }
  4256. try
  4257. {
  4258. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4259. {
  4260. s.SetLength(size);
  4261. }
  4262. Assert.IsTrue(client.Exists(remoteFile));
  4263. var attributes = client.GetAttributes(remoteFile);
  4264. Assert.IsTrue(attributes.IsRegularFile);
  4265. Assert.AreEqual(size, attributes.Size);
  4266. using (var downloaded = new MemoryStream())
  4267. {
  4268. client.DownloadFile(remoteFile, downloaded);
  4269. downloaded.Position = 0;
  4270. Assert.AreEqual(CreateHash(new byte[size]), CreateHash(downloaded));
  4271. }
  4272. }
  4273. finally
  4274. {
  4275. if (client.Exists(remoteFile))
  4276. {
  4277. client.DeleteFile(remoteFile);
  4278. }
  4279. }
  4280. }
  4281. }
  4282. [TestMethod]
  4283. public void Sftp_Open_Append_Write_ExistingFile()
  4284. {
  4285. const int fileSize = 5 * 1024;
  4286. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4287. using (var input = CreateMemoryStream(fileSize))
  4288. {
  4289. input.Position = 0;
  4290. client.Connect();
  4291. var remoteFile = GenerateUniqueRemoteFileName();
  4292. if (client.Exists(remoteFile))
  4293. {
  4294. client.DeleteFile(remoteFile);
  4295. }
  4296. try
  4297. {
  4298. client.UploadFile(input, remoteFile);
  4299. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4300. {
  4301. var buffer = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4302. s.Write(buffer, offset: 0, buffer.Length);
  4303. input.Write(buffer, offset: 0, buffer.Length);
  4304. }
  4305. using (var downloaded = new MemoryStream())
  4306. {
  4307. client.DownloadFile(remoteFile, downloaded);
  4308. input.Position = 0;
  4309. downloaded.Position = 0;
  4310. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4311. }
  4312. }
  4313. finally
  4314. {
  4315. if (client.Exists(remoteFile))
  4316. {
  4317. client.DeleteFile(remoteFile);
  4318. }
  4319. }
  4320. }
  4321. }
  4322. [TestMethod]
  4323. public void Sftp_Open_Append_Write_FileDoesNotExist()
  4324. {
  4325. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4326. {
  4327. client.Connect();
  4328. var remoteFile = GenerateUniqueRemoteFileName();
  4329. if (client.Exists(remoteFile))
  4330. {
  4331. client.DeleteFile(remoteFile);
  4332. }
  4333. try
  4334. {
  4335. #region Verify if merely opening the file for append creates a zero-byte file
  4336. using (client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4337. {
  4338. }
  4339. Assert.IsTrue(client.Exists(remoteFile));
  4340. var attributes = client.GetAttributes(remoteFile);
  4341. Assert.IsTrue(attributes.IsRegularFile);
  4342. Assert.AreEqual(0L, attributes.Size);
  4343. #endregion Verify if merely opening the file for append creates it
  4344. client.DeleteFile(remoteFile);
  4345. #region Verify if content is actually written to the file
  4346. var content = GenerateRandom(size: 100);
  4347. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4348. {
  4349. s.Write(content, offset: 0, content.Length);
  4350. }
  4351. using (var downloaded = new MemoryStream())
  4352. {
  4353. client.DownloadFile(remoteFile, downloaded);
  4354. downloaded.Position = 0;
  4355. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4356. }
  4357. #endregion Verify if content is actually written to the file
  4358. }
  4359. finally
  4360. {
  4361. if (client.Exists(remoteFile))
  4362. {
  4363. client.DeleteFile(remoteFile);
  4364. }
  4365. }
  4366. }
  4367. }
  4368. [TestMethod]
  4369. public void Sftp_Open_PathAndMode_ModeIsCreate_FileDoesNotExist()
  4370. {
  4371. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4372. {
  4373. client.Connect();
  4374. var remoteFile = GenerateUniqueRemoteFileName();
  4375. if (client.Exists(remoteFile))
  4376. {
  4377. client.DeleteFile(remoteFile);
  4378. }
  4379. try
  4380. {
  4381. #region Verify if merely opening the file for create creates a zero-byte file
  4382. using (client.Open(remoteFile, FileMode.Create))
  4383. {
  4384. }
  4385. Assert.IsTrue(client.Exists(remoteFile));
  4386. var attributes = client.GetAttributes(remoteFile);
  4387. Assert.IsTrue(attributes.IsRegularFile);
  4388. Assert.AreEqual(0L, attributes.Size);
  4389. #endregion Verify if merely opening the file for create creates a zero-byte file
  4390. client.DeleteFile(remoteFile);
  4391. #region Verify if content is actually written to the file
  4392. var content = GenerateRandom(size: 100);
  4393. using (var s = client.Open(remoteFile, FileMode.Create))
  4394. {
  4395. s.Write(content, offset: 0, content.Length);
  4396. }
  4397. using (var downloaded = new MemoryStream())
  4398. {
  4399. client.DownloadFile(remoteFile, downloaded);
  4400. downloaded.Position = 0;
  4401. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4402. }
  4403. #endregion Verify if content is actually written to the file
  4404. }
  4405. finally
  4406. {
  4407. if (client.Exists(remoteFile))
  4408. {
  4409. client.DeleteFile(remoteFile);
  4410. }
  4411. }
  4412. }
  4413. }
  4414. [TestMethod]
  4415. public void Sftp_Open_PathAndMode_ModeIsCreate_ExistingFile()
  4416. {
  4417. const int fileSize = 5 * 1024;
  4418. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4419. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4420. using (var input = CreateMemoryStream(fileSize))
  4421. {
  4422. client.Connect();
  4423. var remoteFile = GenerateUniqueRemoteFileName();
  4424. if (client.Exists(remoteFile))
  4425. {
  4426. client.DeleteFile(remoteFile);
  4427. }
  4428. try
  4429. {
  4430. input.Position = 0;
  4431. client.UploadFile(input, remoteFile);
  4432. using (var stream = client.Open(remoteFile, FileMode.Create))
  4433. {
  4434. // Verify if merely opening the file for create overwrites the file
  4435. var attributes = client.GetAttributes(remoteFile);
  4436. Assert.IsTrue(attributes.IsRegularFile);
  4437. Assert.AreEqual(0L, attributes.Size);
  4438. stream.Write(newContent, offset: 0, newContent.Length);
  4439. stream.Position = 0;
  4440. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4441. }
  4442. }
  4443. finally
  4444. {
  4445. if (client.Exists(remoteFile))
  4446. {
  4447. client.DeleteFile(remoteFile);
  4448. }
  4449. }
  4450. }
  4451. }
  4452. [TestMethod]
  4453. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_FileDoesNotExist()
  4454. {
  4455. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4456. {
  4457. client.Connect();
  4458. var remoteFile = GenerateUniqueRemoteFileName();
  4459. if (client.Exists(remoteFile))
  4460. {
  4461. client.DeleteFile(remoteFile);
  4462. }
  4463. try
  4464. {
  4465. #region Verify if merely opening the file for create creates a zero-byte file
  4466. using (client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4467. {
  4468. }
  4469. Assert.IsTrue(client.Exists(remoteFile));
  4470. var attributes = client.GetAttributes(remoteFile);
  4471. Assert.IsTrue(attributes.IsRegularFile);
  4472. Assert.AreEqual(0L, attributes.Size);
  4473. #endregion Verify if merely opening the file for create creates a zero-byte file
  4474. client.DeleteFile(remoteFile);
  4475. #region Verify if content is actually written to the file
  4476. var content = GenerateRandom(size: 100);
  4477. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4478. {
  4479. s.Write(content, offset: 0, content.Length);
  4480. }
  4481. using (var downloaded = new MemoryStream())
  4482. {
  4483. client.DownloadFile(remoteFile, downloaded);
  4484. downloaded.Position = 0;
  4485. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4486. }
  4487. #endregion Verify if content is actually written to the file
  4488. }
  4489. finally
  4490. {
  4491. if (client.Exists(remoteFile))
  4492. {
  4493. client.DeleteFile(remoteFile);
  4494. }
  4495. }
  4496. }
  4497. }
  4498. [TestMethod]
  4499. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_ExistingFile()
  4500. {
  4501. const int fileSize = 5 * 1024;
  4502. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4503. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4504. using (var input = CreateMemoryStream(fileSize))
  4505. {
  4506. client.Connect();
  4507. var remoteFile = GenerateUniqueRemoteFileName();
  4508. if (client.Exists(remoteFile))
  4509. {
  4510. client.DeleteFile(remoteFile);
  4511. }
  4512. try
  4513. {
  4514. input.Position = 0;
  4515. client.UploadFile(input, remoteFile);
  4516. using (var stream = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4517. {
  4518. // Verify if merely opening the file for create overwrites the file
  4519. var attributes = client.GetAttributes(remoteFile);
  4520. Assert.IsTrue(attributes.IsRegularFile);
  4521. Assert.AreEqual(0L, attributes.Size);
  4522. stream.Write(newContent, offset: 0, newContent.Length);
  4523. stream.Position = 0;
  4524. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4525. }
  4526. }
  4527. finally
  4528. {
  4529. if (client.Exists(remoteFile))
  4530. {
  4531. client.DeleteFile(remoteFile);
  4532. }
  4533. }
  4534. }
  4535. }
  4536. [TestMethod]
  4537. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_ExistingFile()
  4538. {
  4539. // use new content that contains less bytes than original content to
  4540. // verify whether file is first truncated
  4541. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4542. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4543. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4544. {
  4545. client.Connect();
  4546. var remoteFile = GenerateUniqueRemoteFileName();
  4547. if (client.Exists(remoteFile))
  4548. {
  4549. client.DeleteFile(remoteFile);
  4550. }
  4551. try
  4552. {
  4553. client.WriteAllBytes(remoteFile, originalContent);
  4554. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4555. {
  4556. s.Write(newContent, offset: 0, newContent.Length);
  4557. }
  4558. using (var downloaded = new MemoryStream())
  4559. {
  4560. client.DownloadFile(remoteFile, downloaded);
  4561. downloaded.Position = 0;
  4562. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4563. }
  4564. }
  4565. finally
  4566. {
  4567. if (client.Exists(remoteFile))
  4568. {
  4569. client.DeleteFile(remoteFile);
  4570. }
  4571. }
  4572. }
  4573. }
  4574. [TestMethod]
  4575. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_FileDoesNotExist()
  4576. {
  4577. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4578. {
  4579. client.Connect();
  4580. var remoteFile = GenerateUniqueRemoteFileName();
  4581. if (client.Exists(remoteFile))
  4582. {
  4583. client.DeleteFile(remoteFile);
  4584. }
  4585. try
  4586. {
  4587. #region Verify if merely opening the file for create creates a zero-byte file
  4588. using (client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4589. {
  4590. }
  4591. Assert.IsTrue(client.Exists(remoteFile));
  4592. var attributes = client.GetAttributes(remoteFile);
  4593. Assert.IsTrue(attributes.IsRegularFile);
  4594. Assert.AreEqual(0L, attributes.Size);
  4595. #endregion Verify if merely opening the file for create creates a zero-byte file
  4596. client.DeleteFile(remoteFile);
  4597. #region Verify if content is actually written to the file
  4598. var content = GenerateRandom(size: 100);
  4599. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4600. {
  4601. s.Write(content, offset: 0, content.Length);
  4602. }
  4603. using (var downloaded = new MemoryStream())
  4604. {
  4605. client.DownloadFile(remoteFile, downloaded);
  4606. downloaded.Position = 0;
  4607. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4608. }
  4609. #endregion Verify if content is actually written to the file
  4610. }
  4611. finally
  4612. {
  4613. if (client.Exists(remoteFile))
  4614. {
  4615. client.DeleteFile(remoteFile);
  4616. }
  4617. }
  4618. }
  4619. }
  4620. [TestMethod]
  4621. public void Sftp_Open_CreateNew_Write_ExistingFile()
  4622. {
  4623. const int fileSize = 5 * 1024;
  4624. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4625. using (var input = CreateMemoryStream(fileSize))
  4626. {
  4627. client.Connect();
  4628. var remoteFile = GenerateUniqueRemoteFileName();
  4629. if (client.Exists(remoteFile))
  4630. {
  4631. client.DeleteFile(remoteFile);
  4632. }
  4633. input.Position = 0;
  4634. try
  4635. {
  4636. client.UploadFile(input, remoteFile);
  4637. Stream stream = null;
  4638. try
  4639. {
  4640. stream = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write);
  4641. Assert.Fail();
  4642. }
  4643. catch (SshException)
  4644. {
  4645. }
  4646. finally
  4647. {
  4648. stream?.Dispose();
  4649. }
  4650. // Verify that the file was not modified
  4651. using (var downloaded = new MemoryStream())
  4652. {
  4653. client.DownloadFile(remoteFile, downloaded);
  4654. input.Position = 0;
  4655. downloaded.Position = 0;
  4656. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4657. }
  4658. }
  4659. finally
  4660. {
  4661. if (client.Exists(remoteFile))
  4662. {
  4663. client.DeleteFile(remoteFile);
  4664. }
  4665. }
  4666. }
  4667. }
  4668. [TestMethod]
  4669. public void Sftp_Open_CreateNew_Write_FileDoesNotExist()
  4670. {
  4671. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4672. {
  4673. client.Connect();
  4674. var remoteFile = GenerateUniqueRemoteFileName();
  4675. if (client.Exists(remoteFile))
  4676. {
  4677. client.DeleteFile(remoteFile);
  4678. }
  4679. try
  4680. {
  4681. #region Verify if merely opening the file creates a zero-byte file
  4682. using (client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4683. {
  4684. }
  4685. Assert.IsTrue(client.Exists(remoteFile));
  4686. var attributes = client.GetAttributes(remoteFile);
  4687. Assert.IsTrue(attributes.IsRegularFile);
  4688. Assert.AreEqual(0L, attributes.Size);
  4689. #endregion Verify if merely opening the file creates it
  4690. client.DeleteFile(remoteFile);
  4691. #region Verify if content is actually written to the file
  4692. var content = GenerateRandom(size: 100);
  4693. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4694. {
  4695. s.Write(content, offset: 0, content.Length);
  4696. }
  4697. using (var downloaded = new MemoryStream())
  4698. {
  4699. client.DownloadFile(remoteFile, downloaded);
  4700. downloaded.Position = 0;
  4701. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4702. }
  4703. #endregion Verify if content is actually written to the file
  4704. }
  4705. finally
  4706. {
  4707. if (client.Exists(remoteFile))
  4708. {
  4709. client.DeleteFile(remoteFile);
  4710. }
  4711. }
  4712. }
  4713. }
  4714. [TestMethod]
  4715. public void Sftp_Open_Open_Write_ExistingFile()
  4716. {
  4717. // use new content that contains less bytes than original content to
  4718. // verify whether file is first truncated
  4719. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4720. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4721. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4722. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4723. {
  4724. client.Connect();
  4725. var remoteFile = GenerateUniqueRemoteFileName();
  4726. if (client.Exists(remoteFile))
  4727. {
  4728. client.DeleteFile(remoteFile);
  4729. }
  4730. try
  4731. {
  4732. client.WriteAllBytes(remoteFile, originalContent);
  4733. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  4734. {
  4735. s.Write(newContent, offset: 0, newContent.Length);
  4736. }
  4737. using (var downloaded = new MemoryStream())
  4738. {
  4739. client.DownloadFile(remoteFile, downloaded);
  4740. downloaded.Position = 0;
  4741. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4742. }
  4743. }
  4744. finally
  4745. {
  4746. if (client.Exists(remoteFile))
  4747. {
  4748. client.DeleteFile(remoteFile);
  4749. }
  4750. }
  4751. }
  4752. }
  4753. [TestMethod]
  4754. public void Sftp_Open_Open_Write_FileDoesNotExist()
  4755. {
  4756. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4757. {
  4758. client.Connect();
  4759. var remoteFile = GenerateUniqueRemoteFileName();
  4760. if (client.Exists(remoteFile))
  4761. {
  4762. client.DeleteFile(remoteFile);
  4763. }
  4764. try
  4765. {
  4766. Stream stream = null;
  4767. try
  4768. {
  4769. stream = client.Open(remoteFile, FileMode.Open, FileAccess.Write);
  4770. Assert.Fail();
  4771. }
  4772. catch (SshException)
  4773. {
  4774. }
  4775. finally
  4776. {
  4777. stream?.Dispose();
  4778. }
  4779. Assert.IsFalse(client.Exists(remoteFile));
  4780. }
  4781. finally
  4782. {
  4783. if (client.Exists(remoteFile))
  4784. {
  4785. client.DeleteFile(remoteFile);
  4786. }
  4787. }
  4788. }
  4789. }
  4790. [TestMethod]
  4791. public void Sftp_Open_OpenOrCreate_Write_ExistingFile()
  4792. {
  4793. // use new content that contains less bytes than original content to
  4794. // verify whether file is first truncated
  4795. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4796. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4797. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4798. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4799. {
  4800. client.Connect();
  4801. var remoteFile = GenerateUniqueRemoteFileName();
  4802. if (client.Exists(remoteFile))
  4803. {
  4804. client.DeleteFile(remoteFile);
  4805. }
  4806. try
  4807. {
  4808. client.WriteAllBytes(remoteFile, originalContent);
  4809. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4810. {
  4811. s.Write(newContent, offset: 0, newContent.Length);
  4812. }
  4813. using (var downloaded = new MemoryStream())
  4814. {
  4815. client.DownloadFile(remoteFile, downloaded);
  4816. downloaded.Position = 0;
  4817. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4818. }
  4819. }
  4820. finally
  4821. {
  4822. if (client.Exists(remoteFile))
  4823. {
  4824. client.DeleteFile(remoteFile);
  4825. }
  4826. }
  4827. }
  4828. }
  4829. [TestMethod]
  4830. public void Sftp_Open_OpenOrCreate_Write_FileDoesNotExist()
  4831. {
  4832. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4833. {
  4834. client.Connect();
  4835. var remoteFile = GenerateUniqueRemoteFileName();
  4836. if (client.Exists(remoteFile))
  4837. {
  4838. client.DeleteFile(remoteFile);
  4839. }
  4840. try
  4841. {
  4842. #region Verify if merely opening the file creates a zero-byte file
  4843. using (client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4844. {
  4845. }
  4846. Assert.IsTrue(client.Exists(remoteFile));
  4847. var attributes = client.GetAttributes(remoteFile);
  4848. Assert.IsTrue(attributes.IsRegularFile);
  4849. Assert.AreEqual(0L, attributes.Size);
  4850. #endregion Verify if merely opening the file creates it
  4851. client.DeleteFile(remoteFile);
  4852. #region Verify if content is actually written to the file
  4853. var content = GenerateRandom(size: 100);
  4854. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4855. {
  4856. s.Write(content, offset: 0, content.Length);
  4857. }
  4858. using (var downloaded = new MemoryStream())
  4859. {
  4860. client.DownloadFile(remoteFile, downloaded);
  4861. downloaded.Position = 0;
  4862. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4863. }
  4864. #endregion Verify if content is actually written to the file
  4865. }
  4866. finally
  4867. {
  4868. if (client.Exists(remoteFile))
  4869. {
  4870. client.DeleteFile(remoteFile);
  4871. }
  4872. }
  4873. }
  4874. }
  4875. [TestMethod]
  4876. public void Sftp_Open_Truncate_Write_ExistingFile()
  4877. {
  4878. const int fileSize = 5 * 1024;
  4879. // use new content that contains less bytes than original content to
  4880. // verify whether file is first truncated
  4881. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4882. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4883. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4884. using (var input = CreateMemoryStream(fileSize))
  4885. {
  4886. client.Connect();
  4887. var remoteFile = GenerateUniqueRemoteFileName();
  4888. if (client.Exists(remoteFile))
  4889. {
  4890. client.DeleteFile(remoteFile);
  4891. }
  4892. input.Position = 0;
  4893. try
  4894. {
  4895. client.WriteAllBytes(remoteFile, originalContent);
  4896. using (var s = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write))
  4897. {
  4898. s.Write(newContent, offset: 0, newContent.Length);
  4899. }
  4900. using (var downloaded = new MemoryStream())
  4901. {
  4902. client.DownloadFile(remoteFile, downloaded);
  4903. input.Position = 0;
  4904. downloaded.Position = 0;
  4905. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4906. }
  4907. }
  4908. finally
  4909. {
  4910. if (client.Exists(remoteFile))
  4911. {
  4912. client.DeleteFile(remoteFile);
  4913. }
  4914. }
  4915. }
  4916. }
  4917. [TestMethod]
  4918. public void Sftp_Open_Truncate_Write_FileDoesNotExist()
  4919. {
  4920. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4921. {
  4922. client.Connect();
  4923. var remoteFile = GenerateUniqueRemoteFileName();
  4924. if (client.Exists(remoteFile))
  4925. {
  4926. client.DeleteFile(remoteFile);
  4927. }
  4928. try
  4929. {
  4930. Stream stream = null;
  4931. try
  4932. {
  4933. stream = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write);
  4934. Assert.Fail();
  4935. }
  4936. catch (SshException)
  4937. {
  4938. }
  4939. Assert.IsFalse(client.Exists(remoteFile));
  4940. }
  4941. finally
  4942. {
  4943. if (client.Exists(remoteFile))
  4944. {
  4945. client.DeleteFile(remoteFile);
  4946. }
  4947. }
  4948. }
  4949. }
  4950. [TestMethod]
  4951. public void Sftp_OpenRead()
  4952. {
  4953. const int fileSize = 5 * 1024 * 1024;
  4954. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4955. {
  4956. client.Connect();
  4957. var remoteFile = GenerateUniqueRemoteFileName();
  4958. SftpCreateRemoteFile(client, remoteFile, fileSize);
  4959. try
  4960. {
  4961. using (var s = client.OpenRead(remoteFile))
  4962. {
  4963. var buffer = new byte[s.Length];
  4964. var stopwatch = new Stopwatch();
  4965. stopwatch.Start();
  4966. var bytesRead = s.Read(buffer, offset: 0, buffer.Length);
  4967. stopwatch.Stop();
  4968. var transferSpeed = CalculateTransferSpeed(bytesRead, stopwatch.ElapsedMilliseconds);
  4969. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  4970. Console.WriteLine(@"Transfer speed: {0:N2} KB/s", transferSpeed);
  4971. Assert.AreEqual(fileSize, bytesRead);
  4972. }
  4973. }
  4974. finally
  4975. {
  4976. if (client.Exists(remoteFile))
  4977. {
  4978. client.DeleteFile(remoteFile);
  4979. }
  4980. }
  4981. }
  4982. }
  4983. [TestMethod]
  4984. public void Sftp_SetLastAccessTime()
  4985. {
  4986. var testFilePath = "/home/sshnet/test-file.txt";
  4987. var testContent = "File";
  4988. using var client = new SftpClient(_connectionInfoFactory.Create());
  4989. client.Connect();
  4990. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4991. var currentTime = DateTime.Now;
  4992. client.UploadFile(fileStream, testFilePath);
  4993. try
  4994. {
  4995. var time = client.GetLastAccessTime(testFilePath);
  4996. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  4997. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  4998. client.SetLastAccessTime(testFilePath, newTime);
  4999. time = client.GetLastAccessTime(testFilePath);
  5000. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5001. }
  5002. finally
  5003. {
  5004. client.DeleteFile(testFilePath);
  5005. }
  5006. }
  5007. [TestMethod]
  5008. public void Sftp_SetLastAccessTimeUtc()
  5009. {
  5010. var testFilePath = "/home/sshnet/test-file.txt";
  5011. var testContent = "File";
  5012. using var client = new SftpClient(_connectionInfoFactory.Create());
  5013. client.Connect();
  5014. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5015. var currentTime = DateTime.UtcNow;
  5016. client.UploadFile(fileStream, testFilePath);
  5017. try
  5018. {
  5019. var time = client.GetLastAccessTimeUtc(testFilePath);
  5020. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5021. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5022. client.SetLastAccessTimeUtc(testFilePath, newTime);
  5023. time = client.GetLastAccessTimeUtc(testFilePath);
  5024. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5025. }
  5026. finally
  5027. {
  5028. client.DeleteFile(testFilePath);
  5029. }
  5030. }
  5031. [TestMethod]
  5032. public void Sftp_SetLastWriteTime()
  5033. {
  5034. var testFilePath = "/home/sshnet/test-file.txt";
  5035. var testContent = "File";
  5036. using var client = new SftpClient(_connectionInfoFactory.Create());
  5037. client.Connect();
  5038. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5039. var currentTime = DateTime.Now;
  5040. client.UploadFile(fileStream, testFilePath);
  5041. try
  5042. {
  5043. var time = client.GetLastWriteTime(testFilePath);
  5044. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5045. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  5046. client.SetLastWriteTime(testFilePath, newTime);
  5047. time = client.GetLastWriteTime(testFilePath);
  5048. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5049. }
  5050. finally
  5051. {
  5052. client.DeleteFile(testFilePath);
  5053. }
  5054. }
  5055. [TestMethod]
  5056. public void Sftp_SetLastWriteTimeUtc()
  5057. {
  5058. var testFilePath = "/home/sshnet/test-file.txt";
  5059. var testContent = "File";
  5060. using var client = new SftpClient(_connectionInfoFactory.Create());
  5061. client.Connect();
  5062. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5063. var currentTime = DateTime.UtcNow;
  5064. client.UploadFile(fileStream, testFilePath);
  5065. try
  5066. {
  5067. var time = client.GetLastWriteTimeUtc(testFilePath);
  5068. DateTimeAssert.AreEqual(currentTime.TruncateToWholeSeconds(), time);
  5069. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5070. client.SetLastWriteTimeUtc(testFilePath, newTime);
  5071. time = client.GetLastWriteTimeUtc(testFilePath);
  5072. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5073. }
  5074. finally
  5075. {
  5076. client.DeleteFile(testFilePath);
  5077. }
  5078. }
  5079. private static IEnumerable<object[]> GetSftpUploadFileFileStreamData()
  5080. {
  5081. yield return new object[] { 0 };
  5082. yield return new object[] { 5 * 1024 * 1024 };
  5083. }
  5084. private static Encoding GetRandomEncoding()
  5085. {
  5086. var random = new Random().Next(1, 3);
  5087. switch (random)
  5088. {
  5089. case 1:
  5090. return Encoding.Unicode;
  5091. case 2:
  5092. return Encoding.UTF8;
  5093. case 3:
  5094. return Encoding.UTF32;
  5095. default:
  5096. throw new NotImplementedException();
  5097. }
  5098. }
  5099. private static byte[] GetBytesWithPreamble(string text, Encoding encoding)
  5100. {
  5101. var preamble = encoding.GetPreamble();
  5102. var textBytes = encoding.GetBytes(text);
  5103. if (preamble.Length != 0)
  5104. {
  5105. var textAndPreambleBytes = new byte[preamble.Length + textBytes.Length];
  5106. Buffer.BlockCopy(preamble, srcOffset: 0, textAndPreambleBytes, dstOffset: 0, preamble.Length);
  5107. Buffer.BlockCopy(textBytes, srcOffset: 0, textAndPreambleBytes, preamble.Length, textBytes.Length);
  5108. return textAndPreambleBytes;
  5109. }
  5110. return textBytes;
  5111. }
  5112. private static decimal CalculateTransferSpeed(long length, long elapsedMilliseconds)
  5113. {
  5114. return (length / 1024m) / (elapsedMilliseconds / 1000m);
  5115. }
  5116. private static void SftpCreateRemoteFile(SftpClient client, string remoteFile, int size)
  5117. {
  5118. var file = CreateTempFile(size);
  5119. try
  5120. {
  5121. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  5122. {
  5123. client.UploadFile(fs, remoteFile);
  5124. }
  5125. }
  5126. finally
  5127. {
  5128. File.Delete(file);
  5129. }
  5130. }
  5131. private static byte[] GenerateRandom(int size)
  5132. {
  5133. var random = new Random();
  5134. var randomContent = new byte[size];
  5135. random.NextBytes(randomContent);
  5136. return randomContent;
  5137. }
  5138. private static Stream CreateStreamWithContent(string content)
  5139. {
  5140. var memoryStream = new MemoryStream();
  5141. var sw = new StreamWriter(memoryStream, Encoding.ASCII, 1024);
  5142. sw.Write(content);
  5143. sw.Flush();
  5144. memoryStream.Position = 0;
  5145. return memoryStream;
  5146. }
  5147. private static string GenerateUniqueRemoteFileName()
  5148. {
  5149. return $"/home/sshnet/{Guid.NewGuid():D}";
  5150. }
  5151. }
  5152. }